Get Active Directory user account last logged on time (PowerShell)

Introduction

This PowerShell Script shows how to use Windows PowerShell to determine the last time that a user logged on to the system.

Scenarios

In some cases, IT admins want to statistics of user last logon time information. This Windows PowerShell script will help IT admins to determine the last time that a user logged on to the system.

Script

Step1: Run the script in the Windows PowerShell Console, type the one command: Import-Module <Script Path> at the prompt.

For example, type Import-Module C:\Script\GetADUserLastLogonTime.psm1

This is shown in the following figure.

Step 2: You can type the command Get-Help Get-OSCLastLogonTime –Full to display the entire help file for this function, such as the syntax, parameters, or examples.
 

Example

Example 1: Type Get-OSCLastLogonTime -SamAccountName "lindawang","doris" command in the Windows PowerShell Console.

This command will list all active directory users' last logon time info.

Example 2: Type Get-OSCLastLogonTime -CsvFilePath "C:\SamAccountName.csv" command in the Windows PowerShell Console.

This command will list user's last logon time info from your specified csv file.

Note: the CSV File format must follow the format below:

Here are some code snippets for your reference.

PowerShell
Edit|Remove
#Check if the account exists. 
If($Results.Count -eq 0{ 
    Write-Warning "The SamAccountName '$UserName' cannot find. Please make sure that it exists."} 
Else 
{ 
    Foreach($Result in $Results) 
    { 
        $DistinguishedName = $Result.Properties.Item("DistinguishedName") 
        $LastLogonTimeStamp = $Result.Properties.Item("LastLogonTimeStamp") 
             
        If ($LastLogonTimeStamp.Count -eq 0) 
        { 
            $Time = [DateTime]0} 
        Else 
        { 
            $Time = [DateTime]$LastLogonTimeStamp.Item(0) 
        } 
        If ($LastLogonTimeStamp -eq 0) 
        { 
            $LastLogon = $Time.AddYears(1600) 
        } 
        Else 
        { 
            $LastLogon = $Time.AddYears(1600).ToLocalTime() 
        } 
  
        #Output in comma delimited format. 
        $Hash = @{ 
                    SamAccountName = $UserName 
                    LastLogonTimeStamp = $(If($LastLogon -match "12/31/1600") 
                                            {"Never Logon"} 
                                            Else 
                                            { 
                                                $LastLogon 
                                            }) 
                    } 
        $Objs = New-Object -TypeName PSObject -Property $Hash 
  
        $Objs                         
    }}

 

Prerequisite

Windows PowerShell 2.0