Nov 17 2021 10:56 AM - edited Nov 17 2021 10:58 AM
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
}
Nov 18 2021 12:25 AM
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
Nov 04 2022 10:36 AM - edited Nov 04 2022 10:45 AM
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.
Feb 02 2023 09:31 AM
$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
Feb 05 2023 09:46 AM
John use this https://helgeklein.com/free-tools/delprof2-user-profile-deletion-tool/ it works very fine.