No matter how hard we try, our Active Directory database still seems to get cluttered! The two most common obsolete objects are computers and users. Today, we are going to clean it those old objects (and provide a bit of safety in case those objects return). What we will end up with is an easy way for you to start manging inactive computers and users in Active Directory!
Before we begin, make sure that you have the Quest AD cmdlets installed. If you don’t have it (or want to see the other tools I’m always using), see this link.
The Inactive Computers Script
#Import Module Add-PSSnapin Quest.ActiveRoles.ADManagement #Disable and Move to Computer_stale #Administration: Disable Old Computers and Move to Computers_Stale $Computers = Get-QADComputer -SearchRoot "OU=Admins,OU=Sites,DC=Test,DC=local" -SearchScope Subtree -Inactivefor 366 $Computers | Set-QADComputer -Location (Get-Date) $Computers | Disable-QADComputer $Computers | Move-QADObject -NewParentContainer 'OU=Computers_Stale,DC=Test,DC=local' #Delete Super Stale Computers $Computers = Get-QADComputer -SearchRoot "OU=Computers_Stale,DC=Test,DC=Local" | where Location -GT (Get-Date).AddMonths(-7) $Computers | Remove-QADObject
Configuring the Inactive Computer Script
Pretty simple right? We start off by importing our Quest Active Roles Management module. Next, we use the Get-QADComputer command to show only computers that have not logged in within a year (-inactivefor 366).
So now you might be asking why am I running the Set-QADComputer command before disabling the computer? For added safety, I do not want to delete these inactive computers immediately. Instead, I want to tattoo them with the date they were disabled. We do that with this line: $Computers | Set-QADComputer -Location (Get-Date).
If you use the location attribute, just change the Set-QADComputer command to another blank attribute. So after tattooing our inactive computers with a date, we then disable it and move it to an OU named Computers_Stale. You will need to modify that OU path for your environment.
Finally, we need a way to delete our super stale computers (computers that have been in the stale OU for a long time). This is done by comparing today’s date with the tattooed date on the disabled computer (the date we stored in the location attribute). Right now, we permanently delete the inactive computers if they have been in the Computers_Stale OU for over 6 months (where Location -GT (Get-Date).AddMonths(-7)).
And in one single command, $Computers | Remove-QADObject, we remove all of our super stale objects! PowerShell makes life simple and you no longer have to worry about inactive computers in Active Directory!
Wrapping this up – a few notes:
1. Replace QADComputer with QADUser to delete stale users.
2. Setup the AD Recycle Bin so that you can recover deleted AD objects.