PowerShell – List All Domain Users and Their Last Logon Time

KB ID 0000752


In the past I’ve looked at third party tools to do this but what if you wanted to use PowerShell?


1. On your server paste the following script into Notepad;

$NumDays = 0
 $LogDir = ".Users-Last-Logon.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={[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

File > Save As > Save the file as Users-Last-Logon.ps1 > Change the file type to ‘All Files’ >Save it in C:WindowsSystem32.

last logon script

2. Open PowerShell, and execute the following commands;

cd c:WindowsSystem32

running last logon script

3. Navigate to c:WindowsSystem32 and locate the Users-Last-Logon.csv file.

last logon time output to csv

4. Open the file in Excel, and you can sort the ‘Last Logon’ column, to get the users in the correct order.

Domain Last Login Times Spreadsheet

Update 24/05/13

Email form reader ‘Simon’

I read your article “PowerShell – List All Domain Users and Their Last Logon Time” and it helped me out a lot. Thank your very much for this.

May i suggest to add a filter option on the script, in order to get more results. Currently the script limits the result to 1000. In my Environment there are more users than that.

I added $objstalesearcher.PageSize=4000 to the script, and i got all the users from my bomain.

Again, thank you very much for the script you provided. saved me tons of time !

Related Articles, References, Credits, or External Links

Finding Out the Last Time Domain Users have Logged in

Original Article Written 23/01/13

Author: Migrated

Share This Post On