Disclaimer
This is my personal blog. The opinions and views I express are my own. The information I provide is on an as-is basis. I make no representations as to accuracy, completeness, currentness, suitability, or validity of any information on this blog and will not be liable for any errors, omissions, or delays in this information or any losses, injuries or damages arising from its use.

Scan Active Directory for old user account, Disable those accounts and move them to alternate OU. (Powershell)

** THIS SCRIPT IS PROVIDED WITHOUT WARRANTY, USE AT YOUR OWN RISK **

This script will search an Active Directory OU of your choice for users that have not logged in for 30 days. The script will then disable those users and move them to another OU of your choice. You will also get a CSV output of the results.

Tested with Windows 7, Windows Vista, Windows Server 2K8 R2

$date = Get-Date
$description = "Disabled by me on $date."
$ou = "OU=testusers,OU=test,DC=com"
$disabledOU = "OU=Users,OU=Disabled,OU=test,DC=com"

$finduser = Get-aduser –filter * -SearchBase $ou -properties cn,lastlogondate | 
Where {$_.LastLogonDate –le [DateTime]::Today.AddDays(-30) -and ($_.lastlogondate -ne $null) }

$finduser | export-csv c:\scripts\disabled_users.csv
$finduser | set-aduser -Description $description –passthru | Disable-ADAccount

write-host -foregroundcolor yellow "Searching OU for disabled Accounts"
[System.Threading.Thread]::Sleep(500)

$disabledAccounts = Search-ADAccount -AccountDisabled -UsersOnly -SearchBase $ou

write-host -foregroundcolor yellow "Moving disabled Accounts to the disabled OU"
[System.Threading.Thread]::Sleep(500)

$disabledAccounts | Move-ADObject -TargetPath $disabledOU

write-host -foregroundcolor yellow "Script Complete"

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.