NOTE: This script has been updated! Please see the new post for the new script and a download link.
A while back I tasked myself with creating a way to scan Active Directory for any "stale accounts", both user and computer. Our policy dictated that any user who had been disabled for more than 60 days should be removed permanently. So I set off to write a script to do just that.
This would appear to be simple. Do a few LDAP queries and then write the results to a text file or (if you're really confident) delete them automatically. However, if you're familiar with how a user authenticates with a domain, you may see the hurdle you would be required to jump for this to really work.
The script needs to query every domain controller on the network to be 100% accurate. You can try querying the LastLogonTimestamp user attribute, but that's updated on a schedule (every 14 days). The LastLogon user attribute is updated every time the user logs in, but that's kept by each individual controller and is not synchronized.
For example, your corporate office generally authenticates with your primary controller, so you execute the query (looking for LastLogonTimestamp) against that controller. Well your boss has been authenticated with one of your other controllers for the past few months, so his Timestamp shows as being a month or two old.
Oops, you just deleted his/her account.
This script will query every controller and keeps the results in a dictionary object. It then compares the dictionary objects against each other to produce one master list of users coupled with their most recent logon date and time. Finally, the scripts cuts out any user who has logged on in the last 60 days and outputs those remaining "stale" accounts to a text file on the root of C:\.
It queries both machine and user accounts.
Please excuse the formatting and length. The script is as follows:
NOTE: I know some lines are cut off. I'm working on getting something setup for downloading the file or just shortening up some of the code for the site.
Credit for the script that I built this script off of goes to Richard Mueller.
His original scripts and documentation can be found here (http://www.rlmueller.net/Last%20Logon.htm)