Deleting User Profiles

Hello everyone,

I am trying to work with a template script that I discovered over the web and modified it to be tuned for my organization. The script is used for deleting all user profiles on the machine but excluding the special and local admin accounts. So far I tuned the script so that it no longer outputs any errors but the script never deletes any of the profiles on my test machine.

 

$Accounts = Get-WmiObject -Class Win32_UserProfile
$Discount = "systemprofile", "UCS", "LocalService", "NetworkService", "defaultuser0", "default profile"

:OuterLoop
foreach ($User in $Accounts) {
    foreach ($name in $Discount) {
        IF ($User.localpath -like "*\$name") {
            CONTINUE Outerloop
            }
        }
        {$User.Delete()}
}

I put braces {} around $User.Delete() because it was the only way to stop getting ambiguous errors from being returned. This script was my original plan to use because it allows me to exclude certain profiles from being deleted.

This has caused me frustration so I wanted to check first if I could delete a single user profile with the SID. The one liner that I’m using executes but it doesn’t delete the profile at all. I tried another way by using the localpath which I found from technet. Still no success, any help would be much appreciated!

 Get-WmiObject win32_UserProfile -ComputerName $env:COMPUTERNAME | Where-Object {$SID.SID -eq 'S-1-5-21-4271752852-3361135306-3771006025-119702'} | ForEach {$SID.Delete()} 
 Get-CimInstance -ClassName Win32_UserProfile | Where-Object ($_.Localpath -eq 'C:\users\rockn') | Remove-CimInstance 

Things to note –
Ran PowerShell as administrator.
SID is correct.
Special = False
Loaded = False

References
https://powershell.org/forums/topic/delete-user-profiles-except-admin/ Template
Manage Windows User Profiles With PowerShell - How To - business.com
How to delete Windows user profile with PowerShell?
Nested ForEach() in PowerShell - Stack Overflow
https://technet.microsoft.com/en-us/library/ee176860.aspx

Your loop is confusing, this would be a better solution.

foreach ($User in $Accounts) {
    #Extract user name
    $uname = [regex]::Match($User.localpath,"^.*\\(.*?)$").Groups[1].value
    if ($uname -and $Discount -notcontains $uname) {
        {$User.Delete()}
    }
}

From a quick search, I believe RaomingConfigured has to be true in order to use .Delete(), so you may need to add that in the if statement as well or filter them before the loop.

Why reinventing the wheel?

Delprof2