Check for unused AD accounts
Some easy PowerShell to look for AD accounts that are not being used.
August 8, 2016
Q. How can I check for AD accounts that have not been logged on to for a period of time?
A. Having accounts in AD that are not used can be very dangerous for an organization as any attacks on it will not be noticed. The easiest way to look for unused accounts is using PowerShell and there is an attribute that is replicated between domain controllers named LastLogonTimeStamp what will show the last logon regardless of which DC the logon was against compared to LastLogon is which is not replicated between DCs. Note that the LastLogonTimeStamp is not constantly replicated due to the churn and high amount of replication traffic it would cause and can delay up to 2 weeks to replicate (a full explanation can be found at http://social.technet.microsoft.com/wiki/contents/articles/22461.understanding-the-ad-account-attributes-lastlogon-lastlogontimestamp-and-lastlogondate.aspx) however even 2 weeks old is find when looking for accounts that have not logged on for more than 30 days etc. When using PowerShell it is even easier as Microsoft exposes the LastLogonTimeStamp which is hard to read into an easily readable value called LastLogonDate. For all of the examples below you must run an elevated PowerShell session.
To view all accounts with oldest logon first use:
get-aduser -f * -pr lastlogondate|sort -property lastlogondate|ft samaccountname,lastlogondate -auto
To search for all accounts with no logon for more than 30 days use:
$olddate = (Get-Date).AddDays(-30)
get-aduser -f * -pr lastlogondate|sort -property lastlogondate|where {$_.lastlogondate -le $olddate }|ft samaccountname,lastlogondate -auto
There is also a builtin cmdlet, Search-ADAccount which seems to have the sole purpose of finding stale accounts as it will find inactive accounts beyond a certain date range). For example:
Search-ADAccount -AccountInactive -DateTime ((get-date).adddays(-180)) -UsersOnly | sort -property lastlogondate | ft samaccountname, lastlogondate -AutoSize
About the Author
You May Also Like