
You can remove user objects from an Active Directory domain by using the Remove-ADUser PowerShell cmdlet. This cmdlet is a part of the ActiveDirectory Module for Windows PowerShell, which must be pre-installed 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>]
In the -Identity parameter you must specify the AD user account to remove. You can specify a username in several ways, by using: distinguished name (DN), GUID, security identifier (SID) or SAM account name.
To remove the user with the user logon name b.jackson, run the command:
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" }
Before running the script, it is advisable to run it once in the –WhatIf mode.
If you want to log the results (which users were deleted) to a text file, add the following pipeline:
| Out-File c:\ps\removeusers_log.txt -Encoding ASCII -Append -PassThru
You can delete all blocked (disabled) user accounts in domain. To select disabled AD users, use the Search-ADAccount cmdlet (available in PowerShell 4.0 and newer):
Search-ADAccount -AccountDisabled | where {$_.ObjectClass -eq 'user'} | Remove-ADUser
Using PowerShell and the LastLogon attribute, you can find inactive user accounts that have not logged into the domain, for example, more than 6 months. To remove such user objects, run the script:
$lastdate= (Get-Date).AddDays(-180) Get-ADUser -Properties LastLogonDate -Filter {LastLogonDate -lt $lastdate } | Remove-ADUser –WhatIF
You can run a simple PowerShell onliner to remove disabled and inactive users from a specific Organizational Unit in Active Directory:
get-aduser -filter "enabled -eq 'false'" -property WhenChanged -SearchBase "OU=Employees,OU=HQ,DC=theitbros,DC=com" | where {$_.WhenChanged -le (Get-Date).AddDays(-180)} | Remove-ADuser -whatif
The post How to Delete AD User Using PowerShell? appeared first on TheITBros.