How-to: Retrieve an accurate 'Last Logon time'

In Active Directory there are two properties used to store the last logon time:

lastLogonTimeStamp this is only updated sporadically so is accurate to ~ 14 days, replicated to all DNS servers. This is good for finding dormant accounts that havent been used in months.

lastLogon this is updated at every logon, but is Not replicated, so will only be accurate if you check the response from every DNS server. This is good for finding the very latest logon.

Using lastLogonTimeStamp to find a users last logon:

$user = Get-ADUser "user64" -Server "dnsServer1" -Properties lastLogonTimeStamp 
$user | select-object @{Name="Last Logon"; Expression={[DateTime]::FromFileTime($_.lastLogonTimestamp)}}

Using lastLogonTimeStamp to find a computer accounts last logon:

$computer = Get-ADComputer "computer64" -Properties LastLogonTimeStamp
$computer | select-object @{Name="Last Logon"; Expression={[DateTime]::FromFileTime($_.lastLogonTimestamp)}}

A function that uses lastLogon to find exactly when an account last logged in, this has to poll every domain controller to find the most recent logon:

function Get-ADUserLastLogon([string]$userName) 
{
   $dcs = Get-ADDomainController -Filter {Name -like "*"}
   
   foreach($dc in $dcs) { 
     $hostname = $dc.HostName
     $user = Get-ADUser $userName -Server $hostname -Properties lastLogon
     $lngexpires = $user.lastLogon
     if (-not ($lngexpires)) {$lngexpires = 0 }
     If (($lngexpires -eq 0) -or ($lngexpires -gt [DateTime]::MaxValue.Ticks)) {
       $LastLogon = "<Never>"
     }
     Else {
       $Date = [DateTime]$lngexpires
       $LastLogon = $Date.AddYears(1600).ToLocalTime()
     }
  }
  Write-Host $username "last logged on at:" $LastLogon
}

Examples

Find the last logon date/time for the user User64:

Get-ADUserLastLogon "User64"

“Sometimes only one person is missing and the whole world seems depopulated“ ~ Alphonse de Lamartine

Related PowerShell Cmdlets

LoggedOn - Find who is logged into a machine.
Password expiry - Reminder email for account passwords about to expire.


 
Copyright © 1999-2024 SS64.com
Some rights reserved