Old user profiles can consume large amount of space on shared network computers. This can be critical on some machines with relatively small Solid State hard drives.
Its a good idea to delete old user profiles from shared network Windows PCs to ensure that the drives do not run out of space. A number of methods have been around for some time, however recent changes to Windows 10 have broken a lot of these.
The attached Powershell script can be deployed via Group Policy as either a scheduled task, or a Computer Startup script.
# Delete old User Profiles
# Andrew Sharrad 14/5/2020, 17/5/2021, 09/03/2022
# Please test before widescale deployment
#The list of accounts, for which profiles must not be deleted
$ExcludedUsers ="Public","Default","itadmin"
$RunOnServers = $false
[int]$MaximumProfileAge = 120 # Profiles older than this will be deleted
$osInfo = Get-CimInstance -ClassName Win32_OperatingSystem
if ($RunOnServers -eq $true -or $osInfo.ProductType -eq 1) {
New-EventLog -LogName Application -Source "Stone Profile Cleanup" -ErrorAction SilentlyContinue
$obj = Get-WMIObject -class Win32_UserProfile | Where {(!$_.Special -and $_.Loaded -eq $false )}
#$output = @()
foreach ($littleobj in $obj) {
if (!($ExcludedUsers -like $littleobj.LocalPath.Replace("C:\Users\",""))) {
$lastwritetime = (Get-ChildItem -Path "$($littleobj.localpath)\AppData\Local\Microsoft\Windows\UsrClass.dat" -Force ).LastWriteTime
if ($lastwritetime -lt (Get-Date).AddDays(-$MaximumProfileAge)) {
$littleobj | Remove-WmiObject
# $output += [PSCustomObject]@{
# 'RemovedSID' = $littleobj.SID
# 'LastUseTime' = $litteobj.LastUseTime
# 'LastWriteTime' = $lastwritetime
# 'LocalPath' = $littleobj.LocalPath
# }
}
}
}
#$output | Sort LocalPath | ft
#$output | Sort LocalPath | ft * -AutoSize | Out-String -Width 4096 | Out-File -filepath "C:\MyOutput.TXT" -append -Encoding Unicode
Write-EventLog –LogName Application –Source "Stone Profile Cleanup" –EntryType Information –EventID 1701 -Category 2 -Message ("Profiles older than $MaximumProfileAge days have been cleaned up")
}
Applies to: