Windows 10 Delete User Profiles Older Than 60 Days

Copper Contributor

Hi. I am working on trying to automate cleaning up local user profiles on some machines that after awhile run into HDD space issues. I've been working on a script below for this, but I cannot get it to work quite right. I want to leave any profile that does not have a creation date older than 30 days. But it still deletes all profiles in the C:\Users folder. It doesn't seem to recognize the CreationTime on the profile, even though I can visually verify the date is within 30 days.

 

$Results = Get-CimInstance -Class Win32_UserProfile | Where-Object { $_.CreationTime -lt (Get-Date).AddDays(-30) -and $_.Name -ne "Public" -and $_.Name -ne "defaultuser0" -and $_.LocalPath -like "C:\Users\*"}
Foreach ($Temp in $Results)
{
$temp | Remove-CimInstance
Remove-Item -Path $temp.localpath -Recurse -force
}

4 Replies

@John Andrews 

 

Hi John,

 

This is what i use in my transcription log file clean up to clean up log files older than 15 days- may be of use...

Get-ChildItem $PSScriptRoot -recurse "*$Script:ScriptName.log" -force | Where-Object {$_.lastwritetime -lt (get-date).adddays(-15)} | Remove-Item -force

 

@John Andrews 

Very late response, but I am actually working on this same issue. This is what worked for me.

 

I removed

-and $_.Name -ne "Public" -and $_.Name -ne "defaultuser0" -and $_.LocalPath -like "C:\Users\*"}

because

| where {$_.Loaded -eq $false} |

will replace this in my case.

 

Finds and selects your users

Get-CimInstance -ClassName Win32_UserProfile | Where {$_.CreationTime -lt (get-date).adddays(-60)} | where {$_.Loaded -eq $false} | select -Property LocalPath,Loaded,PSComputerName | ft -AutoSize

 

Deletes your users

Get-CimInstance -ClassName Win32_UserProfile | Where {$_.CreationTime -lt (get-date).adddays(-60)} | where {$_.Loaded -eq $false} | Remove-CimInstance -Verbose -Confirm:$false

 

Not very pretty but it gets the job done.

 

$currentDate = Get-Date

$oneYearAgo = $currentDate.AddYears(-1)

 

Get-WmiObject -Class Win32_UserProfile | ForEach-Object {

  if ($_.ConvertToDateTime($_.LastUseTime) -lt $oneYearAgo) {

    Remove-WmiObject -InputObject $_ -Confirm:$false

  }

}

 

Deploy as a startup script.  This works very well