Deleting User Profiles

Welcome Forums General PowerShell Q&A Deleting User Profiles

This topic contains 2 replies, has 3 voices, and was last updated by

2 years, 3 months ago.

  • Author
  • #59683

    Points: 0
    Rank: Member

    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"
    foreach ($User in $Accounts) {
        foreach ($name in $Discount) {
            IF ($User.localpath -like "*\$name") {
                CONTINUE Outerloop

    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 Template,2-2.html

  • #59695

    Points: 2
    Rank: Member

    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) {

    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.

  • #59701

    Points: 1,184
    Helping Hand
    Rank: Community Hero

    Why reinventing the wheel?


The topic ‘Deleting User Profiles’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort