Using PowerShell to Remove Old AD Computers

A common problem I see at different businesses is a ton of computer objects just hanging out in Active Directory for machines that were removed from service a long time ago. Here is a quick set of powershell commands I use to get those removed quickly and easily! NOTE: you will need the Microsoft Remote Server Administrator Tools (RSAT) installed and enabled on the machine you are running this on in order to use these modules.

First, you need to make an array that has all of the old computers in it:

$computerstoremove = Get-ADComputer -Properties LastLogonDate -Filter * | where {$_.LastLogonDate -lt "1/1/2016" -and $_.LastLogonDate -notlike ""}

Notice I selected anything that has not authenticated with AD since before January 1st 2016. I did this using LastLogonDate property, which you should know is a PowerShell calculated friendly view of LastLogonTimestamp. The LastLogonTimestamp value does not replicate every time an object authenticates with one of the DCs, and could easily be a couple of weeks out of date. To be on the safe side, I would make sure I am grabbing things that are at least 60-90 days without a successful authentication.

Second, display a table of the computers that have been selected to make sure everything looks right:

$computerstoremove | ft SamAccountName,LastLogonDate

Finally, prompt for elevated credentials and remove the objects from Active Directory:

$computerstoremove | Remove-ADObject -Credential (Get-Credential) -Recursive

Now you just need to verify the objects have all been removed:

Get-ADComputer -Properties LastLogonDate -Filter * | where {$_.LastLogonDate -lt "1/1/2011" -and $_.LastLogonDate -notlike ""} | ft SamAccountName,LastLogonDate

All done! Wasn't that easy?