Determining a User's Last Logon Time
Applies To: Windows Server 2008 R2
This topic explains how to use the Active Directory module for Windows PowerShell to determine the last time that a user logged on to the system.
Example
The following example is a sample script that you can use to find the last logon time of the user SaraDavis:
Import-Module ActiveDirectory
function Get-ADUserLastLogon([string]$userName)
{
$dcs = Get-ADDomainController -Filter {Name -like "*"}
$time = 0
foreach($dc in $dcs)
{
$hostname = $dc.HostName
$user = Get-ADUser $userName | Get-ADObject -Properties lastLogon
if($user.LastLogon -gt $time)
{
$time = $user.LastLogon
}
}
$dt = [DateTime]::FromFileTime($time)
Write-Host $username "last logged on at:" $dt }
Get-ADUserLastLogon -UserName SaraDavis
A script is a series of Active Directory module cmdlets. For more information about running Active Directory module scripts, see Running Windows PowerShell Scripts (https://go.microsoft.com/fwlink/?LinkID=119588).
Additional information
For a full explanation of the parameters that you can pass to Get-ADDomainController, Get-ADUser, or Get-ADObject, at the Active Directory module command prompt, type Get-Help <name of cmdlet>–detailed, and then press ENTER.