Export (0) Print
Expand All

Determining a User's Last Logon Time

Updated: February 28, 2009

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.

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 (http://go.microsoft.com/fwlink/?LinkID=119588).

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.

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft