Hunting for inactive Active Directory user accounts

Airman
1 min readJul 14, 2016

Prerequisites

You will need PowerShell ActiveDirectory module installed. Go to Control Panel, Programs and Features, Turn Windows features on or off and select and install Remote Server Administration Tools. (For Windows 7 download them from here: https://www.microsoft.com/en-ca/download/details.aspx?id=7887)

Let’s go!

$today = Get-Date
$long_ago = $today.AddMonths(-6)
$list = Get-ADUser -Filter {Enabled -eq $true -and LastLogonDate -le $long_ago} -Properties *
$list = $list | where {$_.AccountExpirationDate -eq $null -or $_.AccountExpirationDate -gt $today}
$list | select SAMAccountName, DisplayName, Description, LastLogonDate, Created, AccountExpirationDate,`
PasswordLastSet, PasswordExpired, PasswordNeverExpires, EmailAddress, CanonicalName | `
Export-Csv -Encoding UTF8 -NoTypeInformation ".\inactive_users_$($today.ToString("yyyy_MM_dd")).csv"

Step-by-step

Get the current date and determine a “cut off” date — 6 months back:

$today = Get-Date
$long_ago = $today.AddMonths(-6)

Search Active Directory for all the user accounts that are not disabled and haven’t logged on since the “cut off” date. For selected users retrieve all the properties:

$list = Get-ADUser -Filter {Enabled -eq $true -and LastLogonDate -le $long_ago} -Properties *

Keep only accounts that are not expired:

$list = $list | where {$_.AccountExpirationDate -eq $null -or $_.AccountExpirationDate -gt $today}

If you want to check how many user accounts are in your list at this stage:

$list | measure

“Select” the columns (user account properties) that you need and export results into a CSV file named with today’s date, use UTF8 encoding:

$list | select SAMAccountName, DisplayName, Description, LastLogonDate, Created, AccountExpirationDate,`
PasswordLastSet, PasswordExpired, PasswordNeverExpires, EmailAddress, CanonicalName | `
Export-Csv -Encoding UTF8 -NoTypeInformation ".\inactive_users_$($today.ToString("yyyy_MM_dd")).csv"

--

--

Airman

Random rumblings about #InfoSec. The opinions expressed here are my own and not necessarily those of my employer.