Deleting old users on Pcs

Hello,
I wrote a PowerShell script to delete old users from our pcs. Whenever i run this it says completed but it doesn’t delete the Users folders so all the data is still left.

It does however run the CIMinstance and remove all the registry’s and traces of the user. It just doesn’t delete the folder that’s eating up all the space on our machines. I know theres a group policy to accomplish this but I dont have the power to set that up and its a non-issue for others around here.

I can get this script to work when locally run but never seems to work properly when ran through bigfix. Any ideas?

action uses wow64 redirection false
delete __createfile

// CREATEFILE
createfile until END_OF_FILE

$daysToRetain = 30
$currentDate = Get-Date
$retentionDate = $currentDate.AddDays(-$daysToRetain)

$userProfiles = Get-CimInstance -Class Win32_UserProfile | Where-Object {{-not ($.Special) -and ($.LastUseTime -lt $retentionDate) -and ($_.LocalPath -like ‘C:\users\000*’)}

foreach ($profile in $userProfiles) {{
$profilepath = $profile.LocalPath
Remove-Item -Path $profilepath -Recurse -Force
$profile | Remove-CimInstance -Confirm:$false
}

END_OF_FILE

delete deleteusers.ps1
move __createfile deleteusers.ps1

waithidden { pathname of file ((it as string) of value “Path” of key “HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell” of native registry) } -ExecutionPolicy ByPass -File deleteusers.ps1

Hm. If you’ve already removed the user’s registry using the script before, they won’t appear in the list of users when you query Win32_UserProfile afterward, so their directories would not be selected for deletion afterward.

Could you be stumbling upon that case, where now you’re going to have to compare the \Users directory and look for paths that are no longer referenced in any Win32_UserProfile instance?

You have two ‘$.’ in your where clause - should they not be ‘$_.’?

Thats weird. In my actual task the $_. is there, weird it didnt copy over…

Thats what I thought was going on. I tried switching the order in which it goes through the loop, didnt seem to have an effect.

I ran it on one machine and kept getting a “cant delete C:\users####\appdata\local” Not enough permission. I would assume the system account would be able to delete user folders am I wrong?

That’s the Markdown formatting provided in the Forum. You have this in a ‘quote’ formatting which still does some character replacements & formatting, but not in ‘code’ formatting which keeps all the characters as-is.

oh. Haha that makes sense. Thank you.