PowerShell to find inactive user accounts in Active Directory

Need to find what user accounts in Active Directory haven’t been used in a while? This PowerShell script will tell you who hasn’t logged in for the last 90 days:

AD

# Get inactive user accounts in the last 90 days
import-module activedirectory
$domain = “your.domain.here”
$DaysInactive = 90
$time = (Get-Date).Adddays(-($DaysInactive))

$IAUsers = Get-ADUser -Filter {LastLogonTimeStamp -lt $time -and enabled -eq $true} -Properties Name, samaccountname, userprincipalname, LastLogonTimestamp, LastLogonDate, DistinguishedName |
Select-Object Name, samaccountname, userprincipalname, LastLogonDate, DistinguishedName, @{name=’LastLogonTimestampDT’;Expression={[datetime]::FromFileTimeUTC($_.LastLogonTimestamp)}}, @{l=’OU’;e={([adsi]”LDAP://$($_.distinguishedname)”).psbase.parent.distinguishedname}}

# View graphically
# $IAUsers | Out-GridView

# Export to CSV
$IAUsers | Export-CSV C:\Temp\IAUsers03082016b.csv -NoTypeInformation

# Count how many users
($IAUsers | Measure-Object).Count

Leave a Reply