
Deleting computer accounts
As discussed in the previous section, as a system administrator one must adhere to the security policies of the organization and keep their Active Directory database clean and tidy. As part of this process, you might want to delete stale/offline computer objects from Active Directory.
Use the following simple command to delete a computer account:
Remove-ADComputer -Identity COMP1
The most common use case is searching for computers older than x days and removing them. You can achieve this using the following command:
$Computers = Get-ADComputer -Filter * -Properties LastLogonDate | ? {$_.LastLogonDate -lt (get-date).Adddays(-10) } $Computers | Remove-ADComputer
Tip
You need to be very careful while performing the delete operation. Any mistake in the filters can result in your production computers being deleted. So, I prefer storing the Get-ADComputer
cmdlet results in a variable ($computer
in this example), reviewing the list, and then passing it to the Remove-ADComputer
cmdlet.
The first line in the preceding code searches Active Directory for computers that are not contacted in the last 30 days and stores them in a variable. Later, we can pass the variable to the Remove-ADComputer
cmdlet to delete them. By default, this cmdlet will prompt for each deletion; you can override it using the -Confirm:$false
property with the Remove-ADComputer
cmdlet.
To delete multiple computer accounts that have location value set to OFFICE1
, you can use the following command:
Get-ADComputer –filter 'Location –eq "OFFICE1"' | Remove-ADComputer – confirm:$false
Use the following command to delete all computer accounts in a particular OU:
Get-ADComputer –SearchBase "OU=DisabledComp,DC=techibee,DC=ad" | Remove-ADComputer –confirm:$false
These examples will help you to get started. For instance, you can use the Get-ADComputer
cmdlet to search computer accounts using different patterns and pass them to the Remove-ADComputer
cmdlet to delete them.