Script to remove unused profile but exclude special profiles

Hi all,

I need help with script that pulls all profiles from a list of servers that has not been logged in for the past 48 hours and remove it, but to exclude a few profiles.

I would like to use the $PServers to specify the servers ex below


How do I use the WMI command to pull profiles that has not been used within the last 48 hours?
Do I just use the filter to filter out the profiles I don't want to remove? Would it be easier to put all the profiles I want to be excluded in a string?

Profiles I don't want to remove : Administrator, Ctx_StreamingSvc , Public
Hidden profiles: All Users, Default, Default Users

How would you guys script this request?

Who is Participating?
Senior IT System EngineerIT ProfessionalCommented:
ok, sorry about that, try this one:

#requires -version 2

Function Delete-InactiveProfiles {

     FileName: Delete-InactiveProfiles.ps1
     Author:   Alan dot Kaplan at VA dot GOV
     Date:     10-4-2013

     Written to replace DelProf, this script deletes inactive user profiles from a local or remote computer.  

     It supports arguments by position, and has a test parameter
     If you run it locally, you may supply host name, localhost or "."
     The logfile is tab delimited, you may use XLS extension to open in Excel.  
     If you run the script interactively the log opens when the action is complete.

    .Parameter Computername
    The name of the computer

    .Parameter InactiveDays
    The number of days which have been passed before considering a profile inactive.
    The logfile is tab delimited, you may use XLS extension to open in Excel. 

    .Parameter LogFile
    The full path to the logfile. 
    .Parameter OverwriteLog
    If present, the log will be overwritten.
    .Parameter WhatIf
    If present, the script will run in test mode.  No changes are made.

     Delete-InactiveProfiles.ps1 Server1 90 c:\mylogs\logfile.txt
     Delete profiles from Server1 older than 90 days and log results to c:\mylogs\logfile.txt
     Delete-InactiveProfiles.ps1 -ComputerName Server1 -InactiveDays 30 -logfile "c:\my logs\logfile.txt" -WhatIf
     Preview results of running a deletion of profiles from Server1 older than 30 days and log results to "c:\mylogs\logfile.txt"


     PowerShell Function to delete old profiles



       [string] $ComputerName, 


       [string] $LogFile,     
       [switch] $OverwriteLog, 
       [switch] $WhatIf

Function EchoAndLog { param([string] $strText)
	#Echo to host and append to file
    Tee-Object -Append -FilePath $logfile -inputobject $strText 

###################### Script begins ######################
$ErrorActionPreference = "Stop"

#Define default log
$lfd = $env:userprofile + "\desktop\$ComputerName" + "_UserProfileDeleteLog.txt"

#prompt for logfile
if (!$LogFile){
    $logfile = Read-Host "Enter Path to tab delimited Logfile, or ENTER for default,`n$lfd"

#use default log if not specified
if ($LogFile.Length -eq 0) {$LogFile = $lfd}

#Delete old log if OverwriteLog set
if ($OverwriteLog) {Remove-Item $LogFile -Force}

#If log is new, add header
if ((Test-Path $logfile) -eq $False) {
    $header = "Date`tPath`tDaysSinceUsed"
    Out-File -FilePath $logfile -inputobject $header

#special handling of alternate names for the local system
if (($ComputerName.ToLower() -eq "localhost") -or ($ComputerName -eq ".")){
    $ComputerName = $env:COMPUTERNAME

#WMI query excludes Administrator account and local service accounts
Get-WmiObject Win32_UserProfile -filter "not SID like '%-500' and Special = False" -ComputerName $ComputerName  |
        $ProfilePath = "\\$computername\"+$_.LocalPath.Replace(":","$")
        if ((test-Path $ProfilePath)-eq $false) {
            remove-wmiobject -inputobject $_ -WhatIf:$WhatIf
            EchoAndLog "$(Get-Date)`t$ProfilePath`t`tNot Found"
            #I think getting timestamp from NTUser.DAT is more reliable than WMI LastUseTime
            $LastUsedDays = ((get-date)-(Get-Item -force "$profilePath\ntuser.dat").LastWriteTime).days
            $LastUsedDays = [math]::abs($LastUsedDays)
            if($LastUsedDays -gt $InactiveDays){
                #WMI to delete the profile
                remove-wmiobject -inputobject $_ -WhatIf:([bool]$WhatIf)
                $strTxt = "$(Get-date)`t$ProfilePath`t$LastUsedDays`t"
                if($WhatIf -eq $false){
                    $strTxt += "Deleted"
                    $strTxt += "Would be Deleted"
                EchoAndLog $strTxt
                write-host "Skipping $ProfilePath, used within $LastUsedDays days"} 

#Open logfile if done interactively
if ($args.count -eq 0) { Invoke-Item $logfile }

Open in new window

Senior IT System EngineerIT ProfessionalCommented:
So does that scripts you executed manually or as aprt of the scheduled task in every servers that you're going to configure ?
xouvangAuthor Commented:
I would like to set a scheduled task on one machine to run the script.
On-Demand: Securing Your Wi-Fi for Summer Travel

Traveling this summer?Check out our on-demand webinar to learn about the importance of Wi-Fi security and 3 easy measures you can start taking immediately to protect your private data while using public Wi-Fi. Follow us today to learn more!

Senior IT System EngineerIT ProfessionalCommented:
Is this trick applicable to you:

Deleting User Profiles from a Windows system could be done through its system properties. This is an easy task when you only have a few computers to manage but you certainly do not want to do it manually when you manage hundreds or thousands of Windows systems. This Wiki shares how you can easily configure an automatic cleanup of User Profiles older than a certain number of days using Group Policy.
To enable an automatic Cleanup of User Profiles older than a certain number of days using Group Policy, you will need to set the setting Delete user profiles older than a specified number days on system restart under Computer Configuration\Administrative Templates\System\User Profiles to be Enabled and to specify the number of days after which a User Profile can be deleted if it is unused.

The cleanup is done when a system reboot is executed. You have then to be sure that the systems on which this setting is applied are frequently rebooted so that the cleanup is processed as expected.
We have now shared how the cleanup could be enabled. However, your end users might become unhappy because of the automatic cleanup if they are not aware of it. A “smart” way to make your end users aware of the applied cleanup policy is to display a message describing the behavior at each user logon.
To make this true, you can use a Group Policy to update the following registry entries on your Windows systems:

Legalnoticecaption (REG_SZ)
UnderHKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System: This entry can be used to specify the title of your message (Example” Welcome to [Company Name] Network”).

Legalnoticetext (REG_SZ) Under
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System: This entry can be used to specify the text of your message (Example: Please note that your data will automatically be removed from this computer if you do not use it for 30 days. Thank you.)

Once this is applied, your users will be informed about the Cleanup policy before they get inside their profile.

xouvangAuthor Commented:
Thank you for that trick!
Unfortunately at this moment in time my senior Sys Admin says we can not do this yet as we can't reboot the servers.
He wants me to write a script to do what I was asking.
Senior IT System EngineerIT ProfessionalCommented:
try this one:

no need for scripting and it can be scheduled.

I use it like this:

C:\DelProf2\delprof2 /ed:*admin* /u > C:\DelProf2\Profile-Delete.log

Open in new window

Delete inactive user profile, exclude Admin user directory and provide the logs to custom folder.
xouvangAuthor Commented:
We have looked at this but to comply with Helge Klein's license agreement, we don't want to buy a license if a script can do this.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.