Occasionally there is a need to quickly query Active Directory for all user accounts or user accounts with only certain values in particular properties. This can be done by installing and loading the Microsoft Active Directory Administration module for PowerShell. This is an add-on module, named ActiveDirectory, that provides cmdlets that let you manage your Active Directory domains.
Below is a script I recently put together to produce a CSV File detailing the following:
Displayname – @{e={$_.properties.cn};n=’Display Name’},`
Username – @{e={$_.properties.samaccountname};n=’Username’}
LastLogonTime – @{e={[datetime]::FromFileTimeUtc([int64]$_.properties.lastlogontimestamp[0])};n=’Last Logon’},`
Account Disabled or Not – @{e={[string]$adspath=$_.properties.adspath;$account=[ADSI]$adspath;$account.psbase.invokeget(‘AccountDisabled’)};n=’Account Is Disabled’}
The Complete Script is below – Just copy and past the following into notepad, and save the file as filename.ps1
$NumDays = 0
$LogDir = “.\User-Accounts.csv”
$currentDate = [System.DateTime]::Now
$currentDateUtc = $currentDate.ToUniversalTime()
$lltstamplimit = $currentDateUtc.AddDays(- $NumDays)
$lltIntLimit = $lltstampLimit.ToFileTime()
$adobjroot = [adsi]”
$objstalesearcher = New-Object System.DirectoryServices.DirectorySearcher($adobjroot)
$objstalesearcher.filter = “(&(objectCategory=person)(objectClass=user)(lastLogonTimeStamp<=” + $lltIntLimit + “))”
$users = $objstalesearcher.findall() | select `
@{e={$_.properties.cn};n=’Display Name’},`
@{e={$_.properties.samaccountname};n=’Username’},`
@{e={[datetime]::FromFileTimeUtc([int64]$_.properties.lastlogontimestamp[0])};n=’Last Logon’},`
@{e={[string]$adspath=$_.properties.adspath;$account=[ADSI]$adspath;$account.psbase.invokeget(‘AccountDisabled’)};n=’Account Is Disabled’}
$users | Export-CSV -NoType $LogDir
Great, thanks for shring the helpful command to get the list of active directory user and last log on time. I found a utility from http://www.lepide.com/active-directory-cleaner/ which provide automate facilitate to get the list which are based on active directory user and last log on details of accounts and easily mange the inactive user accounts.