Wednesday, October 8, 2014

PowerShell script to disable computers in Active Directory, update the description, and move to a disabled OU

We have always disabled stale AD accounts using a list of computers that hadn't logged onto the domain for a certain number of days (rather than just disabling them without the list). This allowed us to make sure we weren't disabling any known good computers.

We also moved the computer to a disabled computers OU and updated the computer description to indicate when it would be safe to delete the computer account.

We had been using a VB script to disable accounts, but it was unreliable. It never seemed to take care of every computer on the list, and I would have to manually disable these computer accounts that it missed.

This script also was fairly large and complex. Enter PowerShell! The script below was modified slightly from a script I found in the comments of this article. The script performs the following actions:
  • Reads in a list of computers (c:\Scripts\ADCleaner\computers.txt) to be disabled.
  • Updates the computer description to "ITSS - Delete on xx/xx/xxxx". The date it sets is 90 days from the current date.
  • Disables the account
  • Moves the account to the Disabled - PC & User folder in AD
  • Logs the action (c:\Scripts\ADCleaner\computers.log)
This should only require minimal modification to work in your environment. Download script below.

AD-Disable.ps1.txt

$Today = Get-Date
$Desc = "ITSS - Delete on: " + $Today.AddDays(90)

$Computers = Get-Content c:\Scripts\ADCleaner\computers.txt

ForEach ($Computer in $Computers)
{ $ADComputer = $null
$ADComputer = Get-ADComputer $Computer -Properties Description

If ($ADComputer)
{ Add-Content c:\Scripts\ADCleaner\computers.log -Value "$Today - Found $Computer, disabled and moved to Disabled - PC & User OU"
Set-ADComputer $ADComputer -Description $Desc -Enabled $false
Move-ADObject $ADcomputer -targetpath "ou=Disabled - PC & User,dc=csuchico,dc=edu"
}
Else
{ Add-Content c:\Scripts\ADCleaner\computers.log -Value "$Today - $Computer not in Active Directory"
}
} 

No comments:

Post a Comment