Monthly Archive

Categories

Deleting Local User accounts

Do you need to be able to delete local user accounts?  try this

 

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
function remove-user {
[CmdletBinding(SupportsShouldProcess=$true)]
param (
 [parameter(ValueFromPipeline=$true,
   ValueFromPipelineByPropertyName=$true)]
 [string]$computer,
 
 [parameter(ValueFromPipeline=$true,
   ValueFromPipelineByPropertyName=$true)]
 [string]$id 
)
BEGIN {Add-Type -AssemblyName System.DirectoryServices.AccountManagement} 
PROCESS {  
 switch ($computer){
  "."    {$computer = $env:computername}
  "localhost" {$computer = $env:computername}
 }
 
 $ctype = [System.DirectoryServices.AccountManagement.ContextType]::Machine
 $context = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext -ArgumentList $ctype, $computer

 $user = [System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity($context, $id)

## delete the user
if ($psCmdlet.ShouldProcess("$id", "Will be deleted")) {
    $user.Delete()
  }
} 
}

 

We use the System.DirectoryServices.AccountManagement classes to find the user we want and then call the Delete method.  It works nicely on remote machines assuming you have the required permissions.

Leave a Reply