PerlStalker’s SysAdmin Notes

Notes from the life of a systems administrator

Finding Old Disabled Users in Active Directory With Powershell

Originally posted at [2011-02-10 Thu 12:52]

I’ve been putting off dealing with a problem at work for a while and I finally worked out a way to deal with it. At work, when a faculty or staff member leaves, we don’t delete the account right away. Instead, the account is disabled. It’s sort of a CYA policy. It came in useful today, in fact, when I was told that the professor whose account I disabled a couple of days ago was actually granted emeritus status and so his account needed to hang around a while more. The problem is that all those disabled accounts start to add up and I didn’t have an easy way to tell which accounts can actually be whacked and which to hang on to. Well, thanks to the Active Directory module for Powershell, I came up with an easy way to find those accounts.

The AD module provides a cmdlet called Search-ADAccount which can be used to, surprise, surprise, search for AD accounts. Search-ADAccount has a few pre-built options for common searches including finding disabled accounts and inactive accounts, i.e. accounts that haven’t been used in a while. Unfortunately, you can use both at the same time.

So, the plan is to search for disabled AD accounts and check the last logon date. The idea is that, since the account has been disabled, the last logon date should give a reasonable approximation of when the account was disabled. With a little help (okay, a lot of help) from @StevenMurawski, I came with this little gem.

Search-ADAccount -accountdisabled | where {$_.lastlogondate -lt
(get-date).addmonths(-12)} | FT Name,LastLogonDate

That prints out a list if users and the last time the user logged in who did not log in the last twelve months.

The fun comes when you replace FT Name,LastLogonDate with Remove-ADUser. I shouldn’t have to warn you about using care with that last command. It should happily delete all of the old, disabled accounts. See the Search-ADAccount docs for more details on limiting the scope of your search.

Update [2012-03-18 Sun 21:40]: You can add -searchbase to Search-ADAccount to limit your search to a specific OU. See the previously mentioned docs for details.