🎉 Our Microsoft 365 Reporting & Management Tool is now available in Azure Marketplace 🚀
This website uses cookies to improve your experience. We'll assume you're ok with this. Know more.
Active Directory

How to Find Users Last Logon Time in Active Directory

Tracking users last logon time in Active Directory is crucial for identifying inactive accounts, enhancing security, and managing access. AD records last logon data in three key attributes: LastLogon (most accurate but not replicated), LastLogonTimestamp (replicated but only updates every 9-14 days), and LastLogonDate (a readable version of ‘LastLogonTimestamp’ for reports). Choosing the right attribute depends on whether you need real-time accuracy or general inactivity tracking. This guide helps you effectively monitor users last logons by selecting the appropriate attribute based on your needs.

Find Users Last Logon Time in Active Directory Using ADUC

Active Directory Permission Required
Account Operators Least Privilege
Administrators Most Privilege
  • Open the Active Directory Users and Computers console, then right-click Saved Queries in the left pane and select New»Query.
  • Enter the name and an optional description. Ensure that the Include subcontainers check box is checked and click Define Query.
  • Select Custom Search from the Find drop-down menu. Then, switch to the Advanced tab and enter the following LDAP query to list all users in Active Directory.
    (&(objectClass=user)(objectCategory=person))
  • Click OK to save the query, then click OK again to close the configuration window.
    search-for-users-in-active-directory-using-aduc
  • Then, select the created query under Saved Queries. The list of all Active Directory users will appear in the right pane.
  • Right-click on the respective user and choose Properties.
  • Switch to the Attribute Editor tab and scroll down to find the last logon time of the user.
    find-users-last-logon-time-in-active-directory-using-aduc

List All Users Last Logon Time in Active Directory Using PowerShell

Active Directory Permission Required
Domain User Least Privilege
Administrators Most Privilege
  • First, install the Active Directory module, then import it into PowerShell if you're running on a non-domain controller machine.
  • Windows PowerShell Windows PowerShell
     Import-Module ActiveDirectory
  • Then, run the following PowerShell command to get all users last logon time using the LastLogon and LastLogonTimestamp attribute.
  • Windows PowerShell Windows PowerShell
     Get-ADUser -Filter * -Properties LastLogon, LastLogonTimestamp | 
    Select-Object Name, SamAccountName, DistinguishedName, Enabled, 
    @{ 
        Name = "LastLogon" 
        Expression = { 
            if (!$_.LastLogon) { "Never Logged In" } 
            else { [datetime]::FromFileTime($_.LastLogon) } 
        } 
    }, 
    @{ 
        Name = "LastLogonTimestamp" 
        Expression = { 
            if (!$_.LastLogonTimestamp) { "Never Logged In" } 
            else { [datetime]::FromFileTime($_.LastLogonTimestamp) } 
        } 
    } | Format-Table -AutoSize
List All Users Last Logon Time in Active Directory Using PowerShell
  • This script retrieves each Active Directory user's name, SAM account name, distinguished name, account status (enabled/disabled), and last logon details (LastLogon & LastLogonTimestamp).

Get the Most Accurate Last Logon Date for Users in AD Using PowerShell

Active Directory Permission Required
Domain User Least Privilege
Administrators Most Privilege
  • While previous methods provide useful data, they don’t always reveal the true last logon time of a user as the values are either non-replicated or not recently synced.
  • To retrieve the true last logon time for a user in Active Directory, you need to check the LastLogon attribute from all domain controllers (DCs) and pick the most recent value.
  • Since the ‘LastLogon’ attribute is not replicated across DCs, each controller maintains its own record of the user's last login and requires querying all DCs to get the most recent logon.
  • The PowerShell script below automates querying all available DCs in the domain and collects the most recent last logon time of all users.
  • Windows PowerShell Windows PowerShell
     Import-Module ActiveDirectory   
    function Get-ADUserLastLogon([string]$userName)   
    {   
        $domainControllers = Get-ADDomainController -Filter {Name -like "*"}   
        $latestLogonTime = 0   
        foreach($domainController in $domainControllers){     
            $user = Get-ADUser $userName -Server $domainController.HostName -Properties lastLogon    
        	if($user.LastLogon -gt $latestLogonTime){   
                $latestLogonTime = $user.LastLogon   
            } 
        }   
        if ($latestLogonTime -eq 0){    
            return "Never logged in"   
        }else{  
            return [DateTime]::FromFileTime($latestLogonTime) 
        }    
    }   
    $results = @() 
    $allUsers = Get-ADUser -Filter * -Properties SamAccountName 
    foreach ($user in $allUsers) {   
        $lastLogon = Get-ADUserLastLogon -userName $user.SamAccountName   
        $accountStatus = if ($user.Enabled) { "Enabled" } else { "Disabled" } 
        $results += [PSCustomObject]@{ 
            SamAccountName  = $user.SamAccountName 
            RealLastLogon   = $lastLogon 
            AccountStatus   = $accountStatus 
            DistinguishedName = $user.DistinguishedName 
        } 
    } 
    $results| Format-Table -AutoSize
Get the Most Accurate Last Logon Date for Users in AD Using PowerShell
  • The execution of the script retrieves each Active Directory user's name, real last logon time, account status, and AD path.

Boost Active Directory Security with Real-Time Last Logon Monitoring & Audit Reports

AdminDroid’s Active Directory reporting tool takes the hassle out of tracking a user’s last logon time with precise insights. It enables administrators to identify stale users, monitor inactive computers, etc. to optimize resource management and enhance security in Active Directory.

Track the Last Logon of AD Users with Denied Access

Check the last logon time of login denied users to find when an account was active before getting disabled, expired, or locked out for access pattern analysis or investigations.

Analyze the Activity of AD Users with Login Restrictions

Review the last logon of users with login restrictions to verify whether they are actively using their accounts within the permitted time or remain inactive despite having access.

Audit First Logon of the Day in Active Directory to Track Attendance

Monitor user's first successful logon of each day to review attendance, track login patterns, and verify work hours in Active Directory for security and compliance.

Review User Logon Failures in Active Directory to Detect Account Issues

Analyze logon failure events and identify failed attempts by users whose last successful logon was long ago to highlight possible compromise or credential misuse.

Identify and Clean Up Inactive Enabled Accounts in Active Directory

Use the Inactive Days filter in inactive enabled users by last logon time report to find the enabled users inactive for the specified days and assist with cleanup to maintain a secure environment.

Detect Unauthorized Modifications in Per-user Logon Audit Policies

Leverage the per-user audit policy changes reports to get a detailed log of modifications related to the user’s account logon audit policy and revert unauthorized modifications to ensure security settings remain intact.

In a nutshell, AdminDroid is an easy-to-use solution for comprehensive Active Directory management. It goes beyond reporting and auditing logon activities by allowing admins to manage Active Directory objects directly from reports for both individual and bulk tasks.

Explore a full range of reporting options

Important Tips

Combine the last logon with account status (enabled or disabled) to identify truly inactive user accounts in your Active Directory environment.

Use the ‘whenCreated’ attribute to determine whether a never-logged-in Active Directory user a ccount was recently created or existed for a long time.

Notify the user’s manager when a stale or never-logged-in user is identified, then proceed to disable the account and move it to a dedicated OU for efficient management.

Common Errors and Resolution Steps

The following are possible errors and troubleshooting hints while checking user’s last logon in Active directory.

Error The query filter “<Query>” is not a valid query string.

This issue occurs when an invalid LDAP query filter is entered while searching for all users before finding their last logon time in ADUC.

Fix Ensure the query filter value is correctly formatted without typos as mentioned below.
(&(objectClass=user)(objectCategory=person))

Error Get-ADUser: The term ‘Get-ADUser’ is not recognized as the name of a cmdlet, function, script file, or operable program.

This error occurs when the cmdlet is executed on a non-domain controller machine without installing or loading the Active Directory PowerShell module.

Fix Use the following cmdlet to import the Active Directory PowerShell module before execution if the module is already installed. If not installed, install RSAT and then import the module.
Import-Module ActiveDirectory

Error Get-ADUser : Cannot find an object with identity: '<SamAccountName>' under: '<Domain’sDistinguished Name>'.

This error occurs when the specified username is incorrect while running the PowerShell script to retrieve the last logon computer of a user.

Fix Verify the username and ensure it is correct before running the script using the following cmdlet.
Get-ADUser –Filter * | FT

Error Failed to retrieve logon events from <ComputerName>-The RPC server is unavailable.

This error occurs when the target computer is unreachable due to network issues, firewall restrictions, or the RPC service is disabled.

Fix Ensure the target computer is online, verify that the RPC service is running, and check firewall setting allows RPC traffic.

1. Why do LastLogonTimestamps differ across domain controllers?

You might think ‘LastLogonTimestamp’ is a better choice than ‘LastLogon’ since it replicates! But is it really? Let’s break it down.

The ‘LastLogonTimestamp’ value is not updated immediately and can take up to 14 days to replicate across the domain controllers. This delay occurs because the ‘ms-DS-Logon-Time-Sync-Interval’ attribute, located in the domain's default naming context, controls its update frequency. By default, this setting is 'NOT SET,' which effectively means 14 days.

How is the replication interval calculated for LastLogonTimestamp?

  • When a user logs into AD, the respective domain controller reads the current time and updates the ‘LastLogonTimestamp’ value for the user.
  • Active Directory generates a comparison threshold using the formula: 14 days - (random percentage of up to 5 days). This means the update interval varies between 9 and 14 days to prevent all accounts from updating at the same time.
  • The system calculates the time difference between the last replicated ‘LastLogonTimestamp’ and the current time. If the time difference exceeds the comparison threshold, the ‘LastLogonTimestamp’ replicates across DCs. Otherwise, it remains unchanged in the respective DC.

Why does Active Directory delay the replication of LastLogonTimestamp?

  • Efficient replication design - Frequent updates would generate excessive replication traffic in DCs. To prevent this, the system updates this attribute only when the existing timestamp is older than 9-14 days or a custom threshold (if modified via ‘msDS-LogonTimeSyncInterval’).
  • Not designed for real-time tracking - ‘LastLogonTimestamp’ is meant to help estimate user inactivity rather than capture every logon event in real time. Since inactivity is usually measured over a month or more, a 14-day threshold does not significantly impact the detection of stale accounts.

2. How to find a user’s last logon computer in Active Directory?

Identifying a user's last logon computer in Active Directory is essential for IT administration, security, and troubleshooting. However, Active Directory does not store this information as a single attribute tied to a user account, so finding the specific computer requires additional effort. This involves querying the event logs in all the computers, filtering & sorting the results, and more.

Find a user’s last logon computer in Active Directory using PowerShell

You can run the following script in Active Directory to find out which computer a user is last logged into using PowerShell. To execute it, you need at least the Event Log Reader role.

$User = Read-Host "Enter the user's SAM Account Name" 
try { 
    $ADUser = Get-ADUser -Identity $User -ErrorAction Stop 
} catch { 
    Write-Host "Error: Get-ADUser : $($_.Exception.Message)" -ForegroundColor Red 
    return 
} 
$Computers = Get-ADComputer -Filter {Enabled -eq $true} -Properties OperatingSystem | Where-Object { $_.OperatingSystem -ne $null } | Select-Object -ExpandProperty Name 
$LogonEvents = @() 
foreach ($Computer in $Computers) {Computer 
    try { 
        $LogonEvent = Get-WinEvent -LogName "Security" -FilterXPath "*[System[EventID=4624] and EventData[Data[@Name='TargetUserName']='$User']]" -MaxEvents 1 -ComputerName $Computer -ErrorAction SilentlyContinue | Select-Object TimeCreated, @{Name="ComputerName"; Expression={$Computer}} 
        if ($LogonEvent) { 
            Write-Host "Successfully retrieved logon events from the computer '$Computer'" -ForegroundColor Green 
            $LogonEvents += $LogonEvent 
        } else { 
            Write-Host "No logon events were found on $Computer for the user '$User'" -ForegroundColor Yellow 
        } 
    } 
    catch { 
        Write-Warning "Failed to retrieve the logon events from the computer '$Computer' - $($_.Exception.Message)" 
    } 
} 
Write-Host "--------------------------------------" -ForegroundColor DarkGray 
$LatestLogon = $LogonEvents | Sort-Object TimeCreated -Descending | Select-Object -First 1 
if ($LatestLogon) { 
    Write-Host "The user '$User' was last logged in the computer '$($LatestLogon.ComputerName)' at $($LatestLogon.TimeCreated)" -ForegroundColor Cyan 
} else { 
    Write-Host "No logon events were found for the user '$User' on any enabled computer." -ForegroundColor Red 
}
find-a-users-last-logon-computer-in-active-directory

Important considerations before running the user’s last logon computer script

  • Enable remote management: Ensure all computers in your Active Directory are configured for remote management over DCOM to allow remote event log retrieval. If some computers aren’t enabled for remote management, the script will only retrieve data from configured computers, potentially missing the true last logon.
  • Ensure account logon auditing is enabled: Make sure logon auditing is enabled in your Active Directory environment to record sign-in events. Without it, past logon details are not captured and cannot be retrieved.
  • Finds last logon only from enabled computers: The given PowerShell script retrieves the user's last logon from enabled computers only and identifies the most recent logon. Disabled computers are skipped as they cannot be queried remotely.
  • Logon event type consideration: The script determines the last logged-on computer based on the last successful logon event (Event ID 4624 ) and not on logon failures (Event ID 4625) to ensure accuracy in identifying the actual last-used machine.

3. How to find computer’s last logon time in Active Directory?

Just like finding the last logon time of users helps monitor account activity during forensic investigations, checking a computer's last logon helps identify potential issues. It may indicate hardware failures, a user switching to another machine, a device failing to reach the domain, or a replacement not updated in Active Directory, among other concerns.

Check computer last logon time in active directory using ADUC

  • In the Active Directory Users and Computers console, navigate to the respective containers or OUs, and locate the desired computer.
  • Next, right-click on the respective computer, and choose Properties.
  • Switch to the Attribute Editor tab and scroll down to find the last logon time of the computer.
check-computer-last-logon-time-in-active-directory-using-aduc

Find all computers last logon date using PowerShell in Active Directory

While the ADUC console allows you to identify the last logon time of a computer in Active Directory, finding the last logon time for all computers is time-consuming as it requires navigating through each object manually. To overcome this, the PowerShell script below provides an efficient approach to listing the last logon time of all computers in AD.

Get-ADComputer -Filter * -Properties LastLogonTimestamp, LastLogon, OperatingSystem | 
Select-Object Name, OperatingSystem, DistinguishedName, Enabled, @{Name="LastLogonTimestamp"; Expression={ 
    if ($_.LastLogonTimestamp -eq $null -or $_.LastLogonTimestamp -eq 0){ 
        "Never Logged In" 
    } 
    else{ 
       [datetime]::FromFileTime($_.LastLogonTimestamp) 
    } 
}}, @{Name="LastLogon"; Expression={ 
    if ($_.LastLogon -eq $null -or $_.LastLogon -eq 0){ 
        "Never Logged In" 
    } 
    else{ 
       [datetime]::FromFileTime($_.LastLogon) 
    } 
}} | Format-Table -AutoSize 
find-all-computers-last-logon-date-using-powershell

The script retrieves multiple details for each computer, including its name, operating system, AD path, status, and last logon information such as LastLogonTimestamp & LastLogon from Active Directory.

Kickstart Your Journey With
AdminDroid

Your Microsoft 365 Companion with Enormous Reporting Capabilities

Download Now
User Help Manuals Compliance Docs
x
Delivering Reports on Time
Want a desired Microsoft 365 reports every Monday morning? Ensure automated report distribution and timely delivery with AdminDroid's Scheduling to your email anytime you need.
Delivering Reports on Time
Schedule tailored reports to execute automatically at the time you set and deliver straight to the emails you choose. In addition, you can customize report columns and add inteligent filtering to the activities just from the previous day to suit your Microsoft 365 report requirements.
Set It, Schedule It, See Results- Your Reports, Your Way, On Your Time!
Time Saving
Automation
Customization
Intelligent Filtering
Give Just the Right Access to the Right People
Grant fine-tuned access to any Microsoft 365 user with AdminDroid’s Granular Delegation and meet your organization’s security and compliance requirements.
Give Just the Right Access to the Right People
Create custom roles loaded with just the right permissions and give access to admins or normal users within AdminDroid. The result? A streamlined Microsoft 365 management experience that aligns your organization's security protocols and saves your invaluable time and effort.
Align, Define, Simplify: AdminDroid's Granular Delegation
Smart Organizational Control
Effortless M365 Management
Simplified Access
Advanced Alerts at a Glance
Receive quick notifications for malicious Microsoft 365 activities. Engage with the AdminDroid’s real-time alert policies crafted to streamline your security investigations.
Advanced Alerts at a Glance
Stay informed of critical activities like suspicious emails and high-risk logins, bulk file sharing, etc. Through creating and validating ideal alert policies, AdminDroid provides a comprehensive approach to real-time monitoring and management of potential threats within your organization.
AdminDroid Keeps You Always Vigilant, Never Vulnerable!
Proactive Protection
Real-time Monitoring
Security Intelligence
Threat Detection
Merge the Required Data to One Place
Combine multiple required columns into one comprehensive report and prioritize the information that matters most to you with AdminDroid’s Advanced Column Customization.
Merge the Required Data to One Place
This column merging capability offers a flexible way to add different columns from various reports and collate all the essential data in one place. Want to revisit the customized report? Save it as a 'View’, and your unique report is ready whenever you need it.
Merge with Ease and Save as Views!
Custom Reporting
Unique View
Desired Columns
Easy Data Interpretation
Insightful Charts and Exclusive Dashboards
Get a quick and easy overview of your tenant's activity, identify potential problems, and take action to protect your data with AdminDroid’s Charts and Dashboards.
Insightful Charts and Exclusive Dashboards
With AdminDroid charts and dashboards, visualize your Microsoft 365 tenant in ways you've never thought possible. It's not just about viewing; it's about understanding, controlling, and transforming your Microsoft 365 environment.
Explore Your Microsoft 365 Tenant in a Whole New Way!
Executive overviews
Interactive insights
Decision-making
Data Visualization
Efficient Report Exporting for Microsoft 365
Downloading your reports in the right file format shouldn’t be a hassle with AdminDroid’s Report Export. Experience seamless report exporting in various formats that cater to your needs.
Efficient Report Exporting for Microsoft 365
Navigate through diverse options and export Microsoft 365 reports flawlessly in your desired file format. Tailor your reports precisely as you need them and save them directly to your computer.
Take Control, Customize and Deliver- Your Office 365 Data, Exported in Your Way!
Easy Export
Seamless Downloading
Data Control
Manage Microsoft 365

Get AdminDroid Office 365 Reporter Now!