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.

Search Active Directory for stale computer accounts and disable them. (Powershell)

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

Scans an OU and any child OUs for computer accounts that have not logged in for 30 days. It disables those computer accounts, moves them to the disabledOU and sets the description of each object to whatever you like. It also writes a logfile to the $logpath.


$date = Get-Date
$description = "Disabled by me on $date due to inactivity for 30 days."
$ou = "OU=computers,DC=test,DC=com"
$disabledOU = "OU=disabledcomputers,DC=test,DC=com"
$logpath = "c:\scripts\inactive_computers.csv"

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

$findcomputers | export-csv $logpath
$findcomputers | set-adcomputer -Description $description –passthru | Disable-ADAccount

write-host -foregroundcolor yellow "Searching OU for disabled Computer Accounts"

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

write-host -foregroundcolor yellow "Moving disabled Accounts to the disabled OU"

$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.