Thursday, October 7, 2010

Remove Old Computer Accounts from the Domain

We have a manual process of retiring systems from the domain and like any manual process without checks and balances there are times is does not get completed properly. One of these “checklist items” is to remove the computer from the domain. If this fails to happen we will have a computer account somewhere in Active Directory forever or at least someone notices. My solution to keep Active Directory “reasonably” clean is of course – PowerShell!
We have computers that could be turned off sitting in the closet or some place else for more than the 30 day password reset period. This we have found in our environment could actually exceed 90 days regularly enough to notice. I don’t want these computers deleted from the domain, however I would like them to call the helpdesk to make sure it’s on and give it the once over for anti-virus, patches, etc.
My script is simple three lines:
  1. Get the date 90 days ago
  2. Disable the computer accounts that haven’t had their password reset in at least 90 days
  3. Delete the computer accounts that haven’t been modified in at least 90 days
I do it in this order and with the same date since disabling the computer account is a change that is registered. This way I will only be deleting the computer accounts that have not accessed the domain in at least 150 days and possibly up to 180 days.
$date = [DateTime]::Today.AddDays(-90)
Get-ADComputer -Filter 'PasswordLastSet -lt $date' -Properties PasswordLastSet | sort Name | Set-ADComputer -Enabled $false 
Get-ADComputer -Filter 'Modified -lt $date' | Remove-ADObject -confirm:$false -Recursive

Note: I have the sort on line two simply for troubleshooting and if I ever need to look at the output I just replace the last pipe with a Write-Host or Export-Csv.

1 comment:

  1. Nice PowerShell script, thanks for sharing helpful and informative article related to Remove Old Active Directory computers by using the powershell script. I also found good information from . This blog helps to clean inactive computer account in active directory and move inactive accounts to another OU. It generates the complete reports which are based on inactive/disabled users, locked out users.