A Cleaner Way to Clean Up Active Directory Objects

Ask any young buck how to solve a problem and PowerShell will be the solution. Talk to the old guard and they will have a specialty tool. Both sides have valid points. PowerShell has near universal support and common parameters. Single use tools often have advanced features that are easier to access and don’t need to be reinvented.

I see this conversation/argument play out every day online. Lately, this discussion started with questions on stale object cleanup in Active Directory. I looked over my old answer to this problem and saw that it needed some work.

To piss off both sides, I combined both approaches by using PowerShell with the OldCmp AD query tool. The solution, to me, is easier to use. It leverages the plug and play mentality of PowerShell with the robustness of a specialty tool. Best of all, you can have this running in just a few minutes for both users and computers!

Combining PowerShell and OldCmp

This script is designed to run as a regular monthly scheduled task. Each time it runs, it will copy the previous report to an Old Reports sub folder. If any objects in the stale OU are enabled, they will be moved and any remaining disabled objects will be deleted. The script will then run the oldcmp tool and email the cleanup report.

Create a folder at C:\Scripts and name it DisableStaleComputers . Save the script to this folder.

Create a sub folder named Old Reports in the DisableStaleComputers folder.

At the top of the script, customize the script variables for your environment. Before running this script, generate a report by running .\OldCmp.exe -report -age 270 -llts. You will also need to remove the hash symbol near the end of the OldCmp command (line 25)

Send-MailMessage-Attachments*.htm-SmtpServer$SmtpServer-From$SmtpFrom-To$SmtpTo-Subject"Stale Computers Report"-body"Attached are the objects that have been marked as stale and moved into the stale objects OU."

To cleanup stale users, repeat the steps above and add a -users parameter to the .\OldCmp line in your new saved script. Be sure to change Get-ADComputer to Get-ADUser in the script as well.