One way to detect inactive user accounts is to examine when was the last time they logged on to the Active Directory domain. Without further ado, let’s look at the PowerShell snippet that returns all user accounts in the domain that have not logged on in the last 30 days:
$30Days = (get-date).adddays(-30)
Get-ADUser -SearchBase “DC=TORONTO,DC=LOCAL” -filter {lastlogondate -notlike “*” -OR lastlogondate -le $30days} -Properties lastlogondate | Select-Object name, lastlogondate
The first line subtracts 30 days from the current moment and saves the resulting date and time into the 30days variable.
The second line uses familiar Get-ADUser cmdlet to return all user objects matching the specified filter. In this case, we are looking at the value of the lastlogondate attribute and pick up only those users that have either logged on longer than 30 days ago or users that have not logged on at all. The latter is determined based on the lastlogondate attribute being empty.
This PowerShell snippet exhibits a subtle difference that can significantly speed up the results. Unlike with Disabled User Accounts it takes advantage of a more specific filter right in one of its arguments. This way, the underlying LDAP query will return only a subset of user objects as opposed to returning all user objects and then filtering them out on the client side.
LastLogonDate is a tricky attribute. It is not a replicated attribute and it is only updated on a domain controller that actually authenticates a user. That means, that for the most accurate results the script has to examine the value of this attribute on all domain controllers that might have possibly authenticated users. And this is more than just a few lines of PS code…
Microsoft has tried to make this process simpler having introduced the lastlogontimestamp attribute. Although this one is a replicated attribute, it might take up to 14 days for it to get updated, so be careful choosing the time interval that renders user accounts inactive.
If you want a hassle free solution that provides the most accurate data, look at SecureHero Logon Reporter. Logon Reporter hides the complexity of pulling the actual information about last logon time of Active Directory users including the source computer the logon was initiated from.
<< Active Directory User and Group Reporting: A practical guide for administrators