Using Powershell To Get User Last Logon Date

By |2017-08-17T11:47:25-05:00August 17th, 2017|Categories: Windows|Tags: , , , , |3 Comments
Share This Article:

As an Active Directory Administrator, determining the date that a user last logged onto the network could be important at some point. If you have access to the Attribute Editor in your Active Directory tools, you can look for the LastLogonDate attribute. The other option is to use Powershell, and there are two methods to access this information.

Using Get-ADUser

The first option basically gives you the same data that the Attribute Editor GUI would display. In Powershell, run this command to get the data you need, then scroll down the list and look for LastLogonDate.

Get-ADUser username -properties *

Powershell Script

The next method is to use the Powershell script below. Save this script as a .ps1 file and edit the username in the last line of the script (in bold below), then run it.

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 username


Share This Article:

 

Related Content

3 Comments

  1. Dave Smith March 20, 2019 at 10:41 pm - Reply

    This script doesn’t do what I need it to do.

    When I run the script on any of the computers within my domain it displays the following:

    PS C:\support\3-20-19> .\ll.ps1
    username last logged on at: 12/31/1600 4:00:00 PM
    PS C:\support\3-20-19>

    Even though I have last logged onto all of these computers today at 7:20 PM Pacific Time.

    Also, I need to be able to specify the name of the remote computer where I want to gather this information from.

    I don’t want to gather this information from all domain controllers, which is what this script appears to do.

    Please refer me to another source where I can get this type of script or provie me with the right kind of script that will do what I have outlined above.

    • asdasafas July 10, 2019 at 4:59 pm - Reply

      Demanding much?

      This attribute isn’t replicated between DCs so each DC needs to be checked.

      • Robert Russell July 11, 2019 at 7:03 am - Reply

        Exactly this. The script isn’t made to run on an individual workstation or server. If your environment authenticates to a domain controller at sign-in then you need to poll all of your domain controllers then filter out the most recent date/time.

Leave a Comment