Windows 10 Delete User Profiles Older Than 60 Days

%3CLINGO-SUB%20id%3D%22lingo-sub-2976953%22%20slang%3D%22en-US%22%3EWindows%2010%20Delete%20User%20Profiles%20Older%20Than%2060%20Days%3C%2FLINGO-SUB%3E%3CLINGO-BODY%20id%3D%22lingo-body-2976953%22%20slang%3D%22en-US%22%3E%3CP%3EHi.%20I%20am%20working%20on%20trying%20to%20automate%20cleaning%20up%20local%20user%20profiles%20on%20some%20machines%20that%20after%20awhile%20run%20into%20HDD%20space%20issues.%20I've%20been%20working%20on%20a%20script%20below%20for%20this%2C%20but%20I%20cannot%20get%20it%20to%20work%20quite%20right.%20I%20want%20to%20leave%20any%20profile%20that%20does%20not%20have%20a%20creation%20date%20older%20than%2030%20days.%20But%20it%20still%20deletes%20all%20profiles%20in%20the%20C%3A%5CUsers%20folder.%20It%20doesn't%20seem%20to%20recognize%20the%20CreationTime%20on%20the%20profile%2C%20even%20though%20I%20can%20visually%20verify%20the%20date%20is%20within%2030%20days.%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3E%24Results%20%3D%20Get-CimInstance%20-Class%20Win32_UserProfile%20%7C%20Where-Object%20%7B%20%24_.CreationTime%20-lt%20(Get-Date).AddDays(-30)%20-and%20%24_.Name%20-ne%20%22Public%22%20-and%20%24_.Name%20-ne%20%22defaultuser0%22%20-and%20%24_.LocalPath%20-like%20%22C%3A%5CUsers%5C*%22%7D%3CBR%20%2F%3EForeach%20(%24Temp%20in%20%24Results)%3CBR%20%2F%3E%7B%3CBR%20%2F%3E%24temp%20%7C%20Remove-CimInstance%3CBR%20%2F%3ERemove-Item%20-Path%20%24temp.localpath%20-Recurse%20-force%3CBR%20%2F%3E%7D%3C%2FP%3E%3C%2FLINGO-BODY%3E%3CLINGO-LABS%20id%3D%22lingo-labs-2976953%22%20slang%3D%22en-US%22%3E%3CLINGO-LABEL%3EPowerShell%3C%2FLINGO-LABEL%3E%3CLINGO-LABEL%3EWindows%2010%3C%2FLINGO-LABEL%3E%3C%2FLINGO-LABS%3E
New 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
}

1 Reply

@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