PerlStalker’s SysAdmin Notes

Notes from the life of a systems administrator

Finding Old Computer Accounts in Active Directory With Powershell

Originally posted at [2011-06-20 Mon 13:31]

Following up on a previous post discussing finding old user accounts in Active Directory, here’s how you find old computer accounts.

This works on basically the same premise as the user script. In short, we’re going to check the last time the computer logged into Active Directory. That happens on every reboot and from time to time while the machine is up. The same warning applies to computers as it does for user accounts. The last logon timestamp is only accurate to about a week. Since people are generally checking back six months or more, it isn’t much of an issue.

To get the list of stale machines:

get-adcomputer -properties lastLogonDate -filter * | where { $_.lastLogonDate
-lt (get-date).addmonths(-12) } | FT Name,LastLogonDate

You can throw a sort in there if you’d like.

get-adcomputer -properties lastLogonDate -filter * | where { $_.lastLogonDate
-lt (get-date).addmonths(-12) } | sort Name | FT Name,LastLogonDate

It’s just as easy to delete all of those accounts. I’ve added a -whatif to make it harder to do something stupid with cut-and-paste. Take it off to actually delete the computer accounts.

get-adcomputer -properties lastLogonDate -filter * | where { $_.lastLogonDate
-lt (get-date).addmonths(-12) } | Remove-ADComputer -whatif

Updated 2011-06-20 14:15: Added a missing } to every example. Don’t you hate it when you have a bug in your code and you copy and paste that same line over and over again? Me, too.

Comments