Are you tired of manually deleting users from the Active Directory Users and Computers (ADUC) interface? Or are you facing the challenge of processing bulk AD user deletion requests? PowerShell can help simplify this process for you. In this tutorial, we will walk through using PowerShell to delete AD users.
Table of Contents
Requirements
- Windows Active Directory Domain Controller. This tutorial uses Windows Server 2019, and the domain is theitbros.com.
- An account with sufficient access to delete users in Active Directory.
- Windows PowerShell 5.1 or newer.
- A code editor. In this post we will use Visual Studio Code.
- If you’re using a management computer (not the DC), make sure to install the Remote Server Administration Tool (RSAT).
The Remove-ADUser Cmdlet
The Remove-ADUser cmdlet is an essential cmdlet in PowerShell that allows admins to delete user accounts from Active Directory. This cmdlet requires the Active Directory PowerShell module to be installed and run on a Domain Controller or a machine that has the Active Directory Administrative Center installed.
The syntax for the Remove-ADUser cmdlet is straightforward. Here is an example:
Remove-ADUser -Identity "JohnDoe"
This cmdlet takes various parameters, such as -Identity, which specifies the user account to be deleted. The acceptable identity values are:
- A Distinguished name
- A GUID (objectGUID)
- A Security Identifier (objectSid)
- A SAM account name (sAMAccountName)
You can also use other parameters such as -Confirm and -WhatIf to confirm the deletion or to preview the changes that will be made.
In some parts of this tutorial, we will also be using the Search-ADAccount and Get-ADAccount cmdlets. The Search-ADAccount cmdlet is used to search for user accounts that meet certain criteria, such as accounts that have been inactive for a specific period. The Get-ADAccount cmdlet is used to retrieve user accounts from Active Directory.
Using these cmdlets in combination with Remove-ADUser can make the process of deleting user accounts from Active Directory much more efficient and straightforward.
Delete a Single AD User
To delete a single AD user, you can use the Remove-ADUser cmdlet followed by the -Identity parameter, which specifies the user account to be deleted. Here’s an example:
Remove-ADUser -Identity sdavis
This command will delete the user account with the username “sdavis” from Active Directory.
The default behavior of Remove-ADUser is to prompt for confirmation, as you can see in the previous example. But you can also use the -Confir:$false parameter to suppress the prompt and force the user account deletion.
Remove-ADUser -Identity sdavis -Confirm:$false
The example below adds the -Verbose switch to turn on verbose feedback.
If you want to delete a user account based on a specific attribute, such as the email address, you can use the Get-ADUser cmdlet to retrieve the user account and then pipe it to the Remove-ADUser cmdlet. Here’s an example:
Get-ADUser -Filter {UserPrincipalName -eq "sdavis@theitbros.com"} | Remove-ADUser
This command will retrieve the user account with the UPN “sdavis@theitbros.com” and then delete it from Active Directory.
Delete Multiple Users from an Array
To delete multiple users where the list of users is in an array object, use the following command:
$users = "username1","username2","username3"
foreach ($user in $users) {
Remove-ADUser -Identity $user
}
Replace username1, username2, and username3 with the usernames of the user accounts that you want to delete.
For example, let’s delete three users: emiller, mmartinez, and tjohnson.
$users = "emiller", "mmartinez", "tjohnson"
foreach ($user in $users) {
Remove-ADUser -Identity $user -Confirm:$false
}
If the deletion is successful, there will be no output on the screen.
If there are a bulk of users to delete, it will make more sense to put them on a list and have PowerShell read that list. So as an alternative to writing each username, we can import them from a text file.
For example, let’s assume we have a list of users in a file called UsersToDelete.txt.
This code will read each line from the UsersToDelete.txt file, which should contain a list of usernames, and delete each user account.
$users = Get-Content .\UsersToDelete.txt
foreach ($user in $users) {
Remove-ADUser -Identity $user -Confirm:$false
}
Delete Disabled AD User Accounts
To delete disabled user accounts in Active Directory using PowerShell, you can use the Get-ADUser and Remove-ADUser cmdlets in conjunction with the -Filter parameter to find and remove the appropriate accounts.
First, you can use the Get-ADUser cmdlet with the -Filter parameter to retrieve a list of disabled users. For example, to retrieve all disabled user accounts, you can use the following command:
$disabledUsers = Get-ADUser -Properties isCriticalSystemObject `
-Filter { Enabled -eq $false } | `
Where-Object { $_.isCriticalSystemObject -ne $true }
$disabledUsers | Remove-ADUser -Confirm:$false -Verbose
This code retrieves disabled AD user accounts that are not marked as critical system objects and then removes them from Active Directory.
Here is how it works:
- $disabledUsers = Get-ADUser -Properties isCriticalSystemObject -Filter { Enabled -eq $false }: This line uses the Get-ADUser cmdlet to retrieve a list of disabled user accounts. The Properties parameter is used to include the isCriticalSystemObject attribute, which is used later to filter out any critical system objects. The Filter parameter is used to retrieve only disabled users.
- | Where-Object { $_.isCriticalSystemObject -ne $true }: This line uses the Where-Object cmdlet to filter out any critical system objects from the list of disabled users. The $_ variable represents the current object in the pipeline, which is a user account. The ne operator is used to exclude any user accounts where the isCriticalSystemObject attribute is $true.
- $disabledUsers | Remove-ADUser -Confirm:$false -Verbose: This line pipes the list of disabled user accounts to the Remove-ADUser cmdlet to delete them from Active Directory. The Confirm parameter is set to $false to disable confirmation prompts, and the Verbose parameter is used to display detailed output during the deletion process.
Overall, this code can be useful for removing disabled user accounts from Active Directory while excluding any critical system objects that should not be deleted.
Alternatively, you can use the Search-ADAccount cmdlet to find disabled users and then pipe the output to the Remove-ADUser cmdlet:
$disabledUsers = Search-ADAccount -AccountDisabled | Where-Object { $_.ObjectClass -eq 'user' }
$disabledUsers | Remove-ADUser
This command will find all disabled user accounts using the Search-ADAccount cmdlet and filter the results to only include user objects. Then, it will pipe the list of disabled user accounts to the Remove-ADUser cmdlet to remove them from Active Directory.
Delete Stale AD User Accounts
Stale AD user accounts refer to user accounts that have not been used for a specified period. These accounts may pose a security risk to your network, as they may be vulnerable to unauthorized access. It is, therefore, essential to identify and delete such accounts regularly.
In this section, we will show examples of how to get stale AD users and then delete them.
To get stale AD users or AD users who haven’t logged on to the domain in 90 days, use the following code:
$staleUsers = Search-ADAccount -AccountInactive -TimeSpan 90.00:00:00 | `
Where-Object { $_.ObjectClass -eq 'user' }
foreach ($user in $staleUsers) {
try {
Remove-ADUser -Identity $user -ErrorAction Stop -Confirm:$false
"Deleted user $user" | Out-Default
}
catch {
$_.Exception.Message | Out-Default
}
}
This code deletes all inactive user accounts that have been inactive for 90 days or more using the Search-ADAccount cmdlet and the Remove-ADUser cmdlet.
Here’s how it works:
$staleUsers = Search-ADAccount -AccountInactive -TimeSpan 90.00:00:00 | `
Where-Object { $_.ObjectClass -eq 'user' }
This line uses the Search-ADAccount cmdlet to find all inactive user accounts that have been inactive for 90 days or more (-TimeSpan 90.00:00:00). The Where-Object cmdlet is used to filter out any results that are not user accounts.
foreach ($user in $staleUsers) {
This line starts a foreach loop to iterate through each of the stale user accounts found in the previous step.
try {
Remove-ADUser -Identity $user -ErrorAction Stop -Confirm:$false
"Deleted user $user" | Out-Default
}
catch {
$_.Exception.Message | Out-Default
}
This block of code tries to remove each user using the Remove-ADUser cmdlet, which deletes the user account from Active Directory. If the user cannot be deleted for some reason, the error message is caught by the catch block and printed to the console using the Out-Default cmdlet.
But, finding stale users using the Search-ADAccount cmdlet does not filter out critical system objects. That’s why it would be better to use Get-ADUser with the -Filter parameter instead. Here’s an example.
$staleDays = (Get-Date).AddDays(-90)
$staleUsers = Get-ADUser -Properties LastLogonDate, isCriticalSystemObject -Filter { LastLogonDate -lt $staleDays } | Where-Object { $_.isCriticalSystemObject -ne $true }
$staleUsers | Remove-ADUser -Confirm:$false -Verbose
Note. Check our guide on how to find Active Directory user’s last logon time.
This code deletes stale AD user accounts, which are users who haven’t logged on to the domain for 90 days or more. Here’s how it works:
- The first line of code creates a variable called $staleDays and sets it to 90 days in the past. It does this using the AddDays method of the DateTime object returned by Get-Date. This is the number of days that a user must not have logged on to be considered stale.
- The second line of code uses the Get-ADUser cmdlet to get all AD user objects that have a LastLogonDate property that is less than $staleDays. This means that they haven’t logged on in 90 days or more.
- The third line of code pipes the $inactiveUsers variable to the Where-Object cmdlet, which filters out any objects that have the isCriticalSystemObject property set to $true. This is because you generally don’t want to delete critical system accounts.
- Finally, the filtered list of $staleUsers is piped to the Remove-ADUser cmdlet with the Confirm:$false and Verbose parameters. This will delete all of the stale AD users without prompting for confirmation and will provide a verbose output of the deletion process.
You may also improve this code to limit the search scope to specific Active Directory OUs only.
It is important to note that deleting user accounts can have serious consequences, especially if they belong to active users. Before deleting user accounts, it is essential to ensure that they are not needed anymore. You may also want to consider disabling the accounts first and then deleting them after a specified period to ensure that you can restore them if necessary.
Conclusion
Using PowerShell cmdlets can significantly simplify the process of deleting users from Active Directory. We have shown examples of how to delete a single user or multiple users from a text file or an array and how to delete stale and disabled user accounts. We have also provided a script that can help automate the process of deleting multiple users.
With the knowledge you have gained in this tutorial, you can now easily delete users from Active Directory without having to navigate through the Active Directory Users and Computers (ADUC) console manually. This can save you a lot of time and effort, especially when dealing with large user accounts.
We encourage you to experiment with the cmdlets and script we have provided in this tutorial and see how you can further automate the user deletion process in your environment. With PowerShell, the possibilities are endless.
So, what are you waiting for? Try out these PowerShell cmdlets and the script, and make your AD user deletion process more efficient today!
3 comments
Mike above is correct.
Just for the author’s encouragment. I’m learning to program with PS. I’ve found many useful codes/ lines on many websites. But I’ve never seen such great explanations how codes works (‘Here’s how it works:’). I may can copy codes. But all the more I’d like to really understand it. And Cyril helps me out in this very desired manner… THANK YOU!
Thank you, Marcello! Glad you enjoy our articles!