Active Directory with PowerShell
上QQ阅读APP看书,第一时间看更新

Deleting user accounts

The Active Directory PowerShell module has a cmdlet called Remove-ADUser to delete user accounts from Active Directory. Alternatively, the Remove-ADObject cmdlet can be used. The Remove-ADUser cmdlet is designed to deal with user accounts removal. We will use this cmdlet throughout the examples in this section.

The requests for removal of user accounts increase as the attrition rate increases in your organization. You get requests from HR to delete user accounts on a frequent basis either when an employee leaves the organization or he/she turns down the offer just before joining.

Tip

Most organizations won't delete user accounts when an employee leaves the organization. Instead, they will hide these from the Global Address List/Book (GAL), remove them from all groups, disable the mailbox, and keep the ID in a disabled state. Such accounts can be enabled if the employee rejoins the company later.

Removing a user account from Active Directory is a straightforward process. You just need to pass the DN or ObjectGUID, SID or SamAccountName to the -Identity parameter of the Remove-ADUser cmdlet. In the following example, Samaccountname is passed to the -Identity parameter, as shown in the following command:

Remove-ADUser -Identity ChrisB

When this command is executed, it will ask for confirmation of deletion, as shown in the following screenshot:

Deleting user accounts

Since deletion is a critical operation, Active Directory module warns about it. If you are certain that the inputs are correct and you don't want to get prompted for confirmation, set the -Confirm parameter value to $false, as shown in the following command:

Remove-ADUser -Identity ChrisB -Confirm:$false

Similarly, to delete user accounts by reading from a text file, use the following command:

Get-Content C:\temp\users.txt | % { Remove-ADUser -Identity $_ - Confirm:$false}

The Get-Content cmdlet reads the usernames from users.txt and passes them to the Remove-ADUser cmdlet to delete the accounts one after another.