Automating AD cleanup with PowerShell – Updated

So, a while back I put together a script to automate the cleanup of inactive computer accounts. Since then, I’ve had a need to take that automation to the next level and target multiple OUs, as well add some additional criteria. I’m a big fan of the Quest/Dell AD cmdlets and continue to use them here.

The criteria for a computer account to be considered inactive:
1. It is in a specified source OU
2. operatingSystem field includes the word “windows”
3. lastLogonTimestamp is beyond configured threshold
4. pwdLastSet is beyond configured threshold

Other features added to this version:
1. Basic logging
2. OU array for multi source OU targeting
3. Append date stamped description to the moved computer objects

##AD Cleanup Script
##Written by Jake Parks
#Updated 3/26/2014 - Jake
#Added OU array, logging, OS check, append date stamp description

#Add Snap-ins
Add-PSSnapin "Quest.ActiveRoles.ADManagement"

#Set array of OUs to be scanned
#EXAMPLE: $OUlist = @("domain.com/OU","domain.com/OU/OU")
$OUlist = @("yourdomain.com/OU","yourdomain.com/OU/subOU")

#Get date and set description string variable
$Date = get-Date
$Description = "Script disabled on " + $Date.ToShortDateString()

#Start logging
$ErrorActionPreference="SilentlyContinue"
Stop-Transcript | out-null
$ErrorActionPreference = "Continue"
$logDate = get-date -format M.d.yyyy
#Set log path
$logPath =  "c:\ADCleanLog_" + $logDate + ".log"
Start-Transcript -path $logPath

#Check each OU in $OUlist for inactive computers, disable them, append description, and move to inactive OU.
For($i=0; $i -le $OUlist.Length - 1; $i++) {
	$OU = $OUlist[$i]
	$InactiveComp = Get-QADComputer -InactiveFor 90 -SizeLimit 0 -SearchRoot $OU -osname '*windows*'
	write-host ""
	write-host "*****DISABLE INACTIVE COMPUTERS*****"
	write-host ""
	$InactiveComp | Disable-QADComputer
	write-host ""
	write-host "*****APPEND DESCRIPTION TO INACTIVE COMPUTERS*****"
	write-host ""
	Foreach($Comp in $InactiveComp){
		set-QADComputer $Comp -Description $Description
		}
	write-host ""
	write-host "*****MOVE INACTIVE COMPUTERS*****"
	write-host ""
	$InactiveComp | move-QADObject -NewParentContainer "corporate.administaff.com/90 Days Inactive"
	}

#Stop logging
Stop-Transcript
Facebooktwittergoogle_plusredditpinterestlinkedinmail
This entry was posted in Microsoft, PowerShell. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *