LLI Wiki — My Digital Knowledge Base

PowerShell: last logon time of Active Directory users

PowerShell script that queries every domain controller to export each AD user's real last logon time.

The lastLogon attribute of Active Directory is not replicated between domain controllers. To get an accurate last logon time for each user, query every domain controller and keep the most recent value. The script below does this and exports the result to a CSV file.

Script

It requires the ActiveDirectory module (RSAT). For each user it reads lastLogon on every domain controller, keeps the highest value and writes name,username,datetime to C:\temp\lastLogon.csv.

Import-Module ActiveDirectory

function Get-ADUsersLastLogon()
{
$dcs = Get-ADDomainController -Filter {Name -like '*'}
$users = Get-ADUser -Filter *
$time = 0
$exportFilePath = 'C:\temp\lastLogon.csv'
$columns = 'name,username,datetime'

Out-File -filepath $exportFilePath -force -InputObject $columns

foreach($user in $users)
{
foreach($dc in $dcs)
{
$hostname = $dc.HostName
$currentUser = Get-ADUser $user.SamAccountName |
Get-ADObject -Server $hostname -Properties lastLogon

if($currentUser.LastLogon -gt $time)
{
$time = $currentUser.LastLogon
}
}

$dt = [DateTime]::FromFileTime($time)
$row = $user.Name+','+$user.SamAccountName+','+$dt

Out-File -filepath $exportFilePath -append -noclobber -InputObject $row

$time = 0
}
}

Get-ADUsersLastLogon

Notes

Mastodon LLIMastodon SocialFosstodon