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?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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.
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.

Simplify Active Directory Administration

Administration of Active Directory does not have to be hard.  Too often what should be a simple task is made more difficult than it needs to be.The solution?  Hyena from SystemTools Software.  With ease-of-use as well as powerful importing and bulk updating capabilities.

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.
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


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.