PowerShell to find unused AD user accounts

When you run scripts to find Active Directory user accounts that haven’t been used in a while, one thing the standard approach misses is accounts that have never been used.

Finding Active Directory user accounts that have never been used is a little tricky, in that the lastlogontimestamp is NULL although the attribute type is a large integer.  Querying this in PowerShell requires a back-to-front approach as we can’t query if the value is NULL, we have to query if the value is not ‘not-NULL’…. i.e. lastlogontimestamp -like “*”

Thus, the script to find these unused accounts looks a lot like:

import-module activedirectory
$domain = “your.domain.here”

$User = get-aduser -Filter {-not ( lastlogontimestamp -like “*”) -and (enabled -eq $true)} -Properties DistinguishedName, GivenName, Surname, Name, SamAccountName, userprincipalname, whenCreated |
Select-Object DistinguishedName, GivenName, Surname, Name, SamAccountName, userprincipalname, whenCreated,`
@{l=’OU’;e={([adsi]”LDAP://$($_.distinguishedname)”).psbase.parent.distinguishedname}}

# View graphically
# $User | Out-GridView

# Export to CSV
$User | Export-CSV C:\Temp\ADNeverLoggedOn16082016c.csv -NoTypeInformation

# Count how many computers
($User | Measure-Object).Count

Leave a Reply