Skip to content

Instantly share code, notes, and snippets.

@PSingletary
Created March 6, 2018 13:35
Show Gist options
  • Select an option

  • Save PSingletary/2bec9946964697c4c3d492fffadf6a81 to your computer and use it in GitHub Desktop.

Select an option

Save PSingletary/2bec9946964697c4c3d492fffadf6a81 to your computer and use it in GitHub Desktop.
#DeleteOrphanProfiles.ps1
#Performs a SID lookup for each profile in the local computer. If it can't match the SID with a real
#user, the profile gets whacked.
#Needs local admin priv.
$ALLLocalProfiles = Get-WmiObject -Class Win32_UserProfile
foreach ($ThisProfile in $ALLLocalProfiles){
$ProfileSID = $ThisProfile.sid
$ProfilePath = $ThisProfile.localpath
TRY{
$objUser = ([System.Security.Principal.SecurityIdentifier]($ProfileSID)).translate([System.Security.Principal.NTAccount]).Value
Write-host "That worked - $ProfilePath matches to the real user: $objuser "
}
CATCH{
$FoldersizeInBytes = [long](Get-ChildItem -LiteralPath $ProfilePath -Recurse -Force -ErrorAction SilentlyContinue | Measure-Object -Property Length -Sum -ErrorAction SilentlyContinue | Select-Object -Exp Sum)
$FolderSizeinMegaBytes = "{0:n2}" -f ($FoldersizeInBytes/1MB)
Write-host "The dir $ProfilePath doesn't match to a user, so let us remove its $FolderSizeinMegaBytes MB of cruft"
$ThisProfile.delete()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment