Delete Local Accounts with Powershell Script

I found this script courtesy of Google, which remove all Local Accounts, but I would to keep these: Administrator, DefaultAccount, DevToolsUser, Guest, sshd, User, WDAGUtilityAccount Can someone help me?

Function Remove-LocalUser
{
  <#
      .Synopsis
      This function deletes a local user 
      .Description
      This function deletes a local user
      .Example
      Remove-LocalUser -userName "ed" 
      Removes a new local user named ed. 
      .Parameter ComputerName
      The name of the computer upon which to delete the user
      .Parameter UserName
      The name of the user to delete
      .Notes
      NAME:  Remove-LocalUser
      AUTHOR: ed wilson, msft
      LASTEDIT: 06/29/2011 10:07:42
      KEYWORDS: Local Account Management, Users
      HSG: HSG-06-30-11
      .Link
      Http://www.ScriptingGuys.com/blog
      #Requires -Version 2.0
  #>
  [CmdletBinding()]
  Param(
    [Parameter(Position=0,
        Mandatory=$True,
      ValueFromPipeline=$True)]
    [string]$userName
  )
  $computerName = $env:ComputerName
  $User = [ADSI]"WinNT://$computerName"
  $user.Delete('user',$userName)
} #end function Remove-LocalUser

$localUsers = Get-WmiObject -Class Win32_UserAccount -Filter  "LocalAccount='True'" | Select-Object Name
foreach ($localUser in  $localUsers.Name){
  Write-Host $localUser
  Remove-LocalUser -userName $localUser
}

Solution 1:

PowerShell has built-in cmdlets for managing local user accounts, so those should be preferred over a custom module (provided you're running a high enough version of PowerShell):

$KeepUsers = "Administrator", "DefaultAccount", "DevToolsUser", "Guest", "sshd", "User", "WDAGUtilityAccount"
Get-LocalUser | ? { $KeepUsers -notcontains $_.Name } | Remove-LocalUser

From left to right:

  1. Get all local users.
  2. Pipe it into Where-Object (? is an alias).
  3. Filter only for users whose usernames don't appear in the $KeepUsers array.
  4. Pipe the newly filtered users into Remove-LocalUser which deletes them.

Solution 2:

Try this:

Get-WMIObject -Class Win32_UserAccount -Filter "LocalAccount='True'" | Where-Object {$_.Name -notin @("Administrator", "DefaultAccount", "DevToolsUser", "Guest", "sshd", "User", "WDAGUtilityAccount")} | Foreach {net user "$_.Name" /delete}
  • First list all local user accounts through WMI.
  • Then use Where-Object filter to exclude the user accounts to keep.
  • Then the pass the objects to Foreach block.
  • Now delete the user accounts using net user.

Footnotes

  • This script must be run with adminstrative priviliges.
  • You must do this from an user account not to be marked for deletion.

Solution 3:

There is a PowerShell module on the PowerShellGallery.com for just this use case.

Find-Module -Name '*localuser*' | Format-Table -AutoSize
# Results
<#
Version Name                Repository Description                                                   
------- ----                ---------- -----------                                                   
3.0     LocalUserManagement PSGallery  a module that performs various local user management functions
#>

In PowerShell v5x and PowerShell Core6x or higher.

Get-Command -Name '*localuser*' | Format-Table -Autosize
# Results
<#
CommandType Name              Version Source                            
----------- ----              ------- ------                            
Cmdlet      Disable-LocalUser 1.0.0.0 Microsoft.PowerShell.LocalAccounts
Cmdlet      Enable-LocalUser  1.0.0.0 Microsoft.PowerShell.LocalAccounts
Cmdlet      Get-LocalUser     1.0.0.0 Microsoft.PowerShell.LocalAccounts
Cmdlet      New-LocalUser     1.0.0.0 Microsoft.PowerShell.LocalAccounts
Cmdlet      Remove-LocalUser  1.0.0.0 Microsoft.PowerShell.LocalAccounts
Cmdlet      Rename-LocalUser  1.0.0.0 Microsoft.PowerShell.LocalAccounts
Cmdlet      Set-LocalUser     1.0.0.0 Microsoft.PowerShell.LocalAccounts
#>

So you could just do this...

Get-LocalUser | 
Where Name -NotMatch 'Administrator|DefaultAccount|Guest|WDAGUtilityAccount'

You could do the same thing for the Remove cmdlet.