How to Delete AD User Using PowerShell?

The Delete-ADUser PowerShell cmdlet can be used to remove user objects from an Active Directory domain. This cmdlet is part of the ActiveDirectory Module for Windows PowerShell, which must be installed ahead of time and imported into the PoSh session with the command:

Import-Module activedirectory

The syntax of the Remove-ADUser cmdlet looks as follows:

Remove-ADUser [-Identity] <ADUser> [-WhatIf] [-Confirm] [-AuthType <ADAuthType> {Negotiate | Basic}] [-Credential <pscredential>] [-Partition <string>] [-Server <string>] [<CommonParameters>]

You must specify the AD user account to remove with the -Identity argument. You can use distinguishing name (DN), GUID, security identifier (SID), or SAM account name to specify a username.
Run the following command to remove the user with the user login name b.jackson:

Remove-ADUser b.jackson

A prompt appears that asks you to confirm the removal of the user object from the domain. To delete a user, press Y > Enter.

To remove AD user without confirmation prompt, add -Confirm:$False at the end:

Remove-ADUser b.jackson -Confirm:$False

You can remove several domain users at once using a simple PowerShell script. Create a text file Users.txt with a list of users to remove.

b.jackson

brett.jackson

t.mauer

a.kit

s.cooper

To remove AD users from the list from a text file, use the following PowerShell script:

Import-Module Activedirectory

$users = Get-Content "c:\PS\Users.txt"




ForEach ($user in $users)

{

Start-Sleep -s "1"

Remove-ADUser -Identity $remove -Confirm:$false

Write-host $user "Deleted"

}

It’s a good idea to run the script once in the –WhatIf mode before running it.

Add the following pipeline to log the results (which users were erased) to a text file:

| Out-File c:\ps\removeusers_log.txt -Encoding ASCII -Append -PassThru

All blocked (disabled) user accounts in the domain can be deleted. Use the Search-ADAccount cmdlet (available in PowerShell 4.0 and newer) to find disabled AD users:

Search-ADAccount -AccountDisabled | where {$_.ObjectClass -eq 'user'} | Remove-ADUser

You may detect inactive user accounts that have not logged into the domain for more than 6 months using PowerShell and the LastLogon property. Run the following script to get rid of such user objects:

$lastdate= (Get-Date).AddDays(-180)

Get-ADUser -Properties LastLogonDate -Filter {LastLogonDate -lt $lastdate } | Remove-ADUser –WhatIF

To delete disabled and inactive users from a specific Organizational Unit in Active Directory, run the following PowerShell onliner:

get-aduser -filter "enabled -eq 'false'" -property WhenChanged -SearchBase "OU=Employees,OU=HQ,DC=solutionviews.com,DC=com" | where {$_.WhenChanged -le (Get-Date).AddDays(-180)} | Remove-ADuser -whatif

Leave a Reply

Your email address will not be published. Required fields are marked *




Enter Captcha Here :