🎉 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 Check the Last Logon Time of Computers in Active Directory

The last logon activity of computers in Active Directory helps admins determine whether a computer is in use or inactive due to hardware failure, network issues, or other reasons. If these activities go unmonitored, stale computer accounts remain in the directory and pose security risks. This guide explains practical methods to track the last logon time of computers in Active Directory for effective device management.

Find Computers 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.
  • Provide a name and a description (optional) for the query. Make sure that the Include subcontainers check box is checked and click Define Query.
  • Next, from the Find drop-down menu, select Custom Search. Then, switch to the Advanced tab and enter the following LDAP query to list all computers in Active Directory. 
    (&(objectClass=computer)(objectCategory=computer))
  • Click OK to define the query, then click OK again to save and close the configuration window.
    find-all-computers-in-ad-using-aduc
  • Then, select the created query under Saved Queries. The list of all Active Directory computers will appear in the right pane.
  • Right-click the computer you want to check and choose Properties.
  • Switch to the Attribute Editor tab and scroll down to find the last logon time of the computer. (If the attribute editor tab is missing, go to the View menu and enable the ‘Advanced Features’ option).
Find Computers Last Logon Time in Active Directory Using ADUC

Check Active Directory Computers Last Logon TimeStamp Using PowerShell

Active Directory Permission Required
Account Operators Least Privilege
Administrators Most Privilege
  • Import the Active Directory PowerShell module. On a domain-joined computer, you must install the Active Directory module using RSAT before running the cmdlet.
  • Windows PowerShell Windows PowerShell
     Import-Module ActiveDirectory
  • Then, run the following PowerShell command to get the last logon time for all computers using the LastLogon and LastLogonTimeStamp attributes.
  • Windows PowerShell Windows PowerShell
     Get-ADComputer -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
Check Active Directory Computers Last Logon TimeStamp Using PowerShell

Execution of this cmdlet retrieves each Active Directory computer’s name, SAM account name, distinguished name, account status, and last logon details.

Get Active Directory Computers Real Last Logon Time Using PowerShel

Active Directory Permission Required
Account Operators Least Privilege
Administrators Most Privilege
  • While previous methods provide useful data, they don’t always reveal the exact last logon time of a computer as the values may be a non-replicated one.
  • For accurate results, the LastLogon attribute must be queried from all domain controllers, and the most recent value should be selected.
  • To make this process more efficient, we have prepared the PowerShell script below to extract the latest logon records of all computers from Active Directory.
  • Windows PowerShell Windows PowerShell
     Import-Module ActiveDirectory
    function Get-ADComputerLastLogon([string]$computerName) {
        $domainControllers = Get-ADDomainController -Filter { Name -like "*" }
        $latestLogonTime   = 0
        foreach ($domainController in $domainControllers) {
            $computer = Get-ADComputer $computerName -Server $domainController.HostName -Properties LastLogon
            if ($computer.LastLogon -gt $latestLogonTime) {
                $latestLogonTime = $computer.LastLogon
            }
        }
        if ($latestLogonTime -eq 0) {
            return "Never logged in"
        } else {
            return [DateTime]::FromFileTime($latestLogonTime)
        }
    }
    $results      = @()
    $allComputers = Get-ADComputer -Filter * -Properties SamAccountName
    foreach ($computer in $allComputers) {
        $lastLogon     = Get-ADComputerLastLogon -computerName $computer.SamAccountName
        $accountStatus = if ($computer.Enabled) { "Enabled" } else { "Disabled" }
        $results += [PSCustomObject]@{
            Name              = $computer.Name
            SamAccountName    = $computer.SamAccountName
            DistinguishedName = $computer.DistinguishedName
            AccountStatus     = $accountStatus
            RealLastLogon     = $lastLogon
        }
    }
    $results | Format-Table -AutoSize
Get Active Directory Computers Real Last Logon Time Using PowerShel

The execution of the script retrieves the most accurate last logon time for each Active Directory computer, along with details such as the SAM account name, account status, and distinguished name.

Leverage Active Directory Computers Last Logon Audits to Boost Security and Device Management!

AdminDroid’s Active Directory reporting tool gives you complete visibility into last logon events across domain-joined workstations, member servers, and domain controllers. With intuitive dashboards and actionable reports, it helps streamline device lifecycle management, keep computers optimized, and strengthen Active Directory security.

Find and Remove Inactive Computers to Keep Your Directory Clean

Identify inactive computers in Active Directory that haven’t been used for long periods by checking their last logon and safely remove unused ones to free up resources.

Audit Recently Deleted AD Computers to Spot Suspicious Deletions

Examine the last logon details of recently deleted computers in Active Directory to verify if they were removed only due to genuine inactivity or security issues.

Analyse Users’ Last Logon Time for Security Insights

Track inactive user accounts by reviewing Active Directory users’ last logon time to reclaim their assigned workstations and reuse them effectively.

Assess Server Last Logon to Determine Decommissioning

Check the last logon of servers in Active Directory to determine if they are still in use and disable idle servers to optimize resource management.

Gain a Comprehensive View of Active Directory Computers

Utilize Active Directory computer dashboard to check their status, recent activities, membership, and more for effective management.

Track Last Logon of Computers Trusted for Delegation

Review the last logon time of all Active Directory computers trusted for delegation to detect stale or unused servers that still hold delegation rights.

Overall, AdminDroid’s Active Directory management tool provides complete visibility into all aspects of the computers and its last logon time with rich AI powered charts, advanced customization, filtration, etc. This empowers you to clean up stale accounts, block unauthorized access, and manage all Active Directory objects with ease.

Explore a full range of reporting options

Important tips

Restrict sensitive administrator accounts from logging into untrusted Active Directory computers to prevent credential theft.

Do not disable logon or logoff auditing, as these logs, though numerous, are essential for tracking computers’ last logon activity.

Configure remote management on the server to retrieve last logon information from remote computers without missing any logs.

Common Errors and Resolution Steps

Below are some of the errors you may commonly encounter while detecting last logon details for computers. Here’s how to troubleshoot them:

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

This error occurs when an invalid LDAP query filter is entered while searching for all computers in ADUC.

Fix Ensure the query filter is correctly formatted without typing errors as mentioned below.
(&(objectClass=computer)(objectCategory=computer))

Error Import-Module : The specified module ‘ActiveDirectory’ was not loaded because no valid module file was found in any module directory.

This PowerShell error occurs when running the cmdlet ‘Import-Module ActiveDirectory’ on a domain-joined computer that does not have the Active Directory module installed.

Fix If you’re using a domain-joined computer (not a domain controller), you need to manually install the RSAT (Remote Server Administration Tools).
Add-WindowsCapability -Online -Name Rsat.ActiveDirectory.DS-LDS.Tools~~~~0.0.1.0

Error Get-ADComputer : Parameter set cannot be resolved using the specified named parameters.

This error occurs when you use the -Identity and -Filter parameter together in the same command, since the ‘Get-ADComputer’ cmdlet doesn’t support combining them.

Fix Use the -Identity parameter for a single computer or the -Filter parameter for multiple computers when retrieving the last logon timestamp.

Error Get-ADComputer : Directory object not found.

This error occurs when the PowerShell script to retrieve computers last logon is run using an incorrect organizational unit (OU) name.

Fix Verify that the OU name is correct and ensure whether it exists before running the script by using the following cmdlet.
Get-ADOrganizationalUnit -Filter * | Select-Object Name, DistinguishedName
Frequently Asked Questions

Efficiently Manage Your Active Directory Computers by Tracking Their Last Logon Details!

1. How to manage and secure Active Directory computers using last logon data?

A last logon report for Active Directory computers helps you monitor system activity and identify inactive machines. Below is a practical approach to use computers' last logon data to manage and protect your Active Directory environment.

1. Measure the inactivity from the last logon report

  • First, collect each computer’s last logon time from Active Directory. 
  • Next, calculate how many days the computer has been idle. While doing this, make sure to use the most accurate last logon attribute, since LastLogon and LastLogonTimestamp have replication limitations. 
  • This step is critical, as relying on inaccurate data can result in decommissioning a computer that is still in use.

2. Identify stale computers based on inactivity

  • After calculating the inactive days, choose a threshold for the inactivity period. For example, 30, 60, or 90 days, that fits your organization.
  • Now, the computers that remain idle beyond this threshold should be disabled and moved into a quarantine OU
  • This step is critical because unattended devices can be targeted by attackers to compromise or steal data.

3. Safely clean up inactive computers

  • Here comes the most important part, i.e., to review these computers carefully before deciding to delete, or reassign them.
  • Check with the responsible user or department to determine the reason and confirm that the computer is truly inactive before taking any action. 
  • Once all these checks are complete, you can proceed to delete the computer. As a security precaution, ensure that the Active Directory Recycle Bin is enabled to restore any accidentally removed objects.

2. How to set up a scheduled task to remove stale computer accounts in Active Directory based on their last logon time?

A stale computer account is one that hasn’t logged in for a long time but remains enabled in Active Directory. These inactive accounts clutter the directory and pose security risks if exploited. To protect your environment from attacks originating from these devices, it is best to remove inactive computers from Active Directory. Instead of searching and removing them manually, you can automate cleanup using Windows Task Scheduler.

Remove inactive computers from Active Directory using Task Scheduler

  • Save the following PowerShell script in a .ps1 file to remove Active Directory computers that have been inactive for the last 60 days. You can adjust the $daysInactive variable to any number of days according to your organization’s requirements.
    $daysInactive = 60
    $time = (Get-Date).AddDays(-$daysInactive)
    $staleComputers = Get-ADComputer -Filter {LastLogonDate -lt $time} -Properties LastLogonDate
    foreach ($computer in $staleComputers) {
        Remove-ADComputer -Identity $computer.DistinguishedName -Confirm:$false 
    }
    
  • Open Task Scheduler from the Start menu. Click Create Basic Task from the left panel and provide a name and description. Then, click Next.
  • In the Triggers tab, choose Select when you want to start the task and set the start date, time, and recurrence. Then, click Next.
  • Now, in the Actions tab, select What action do you want the task to perform to Start a program and click Next. Here, set the Program/script field to: 
    C:\Windows\System32\WindowsPowerShell\v1.0\PowerShell.exe
  • Then, in the Add arguments field, enter the following by replacing <Filepath> with the location of the saved script file, and click Next.
    -ExecutionPolicy Bypass -File "<FilePath>"
  • Once done, click Finish to save the task.
remove-inactive-computers-using-task-scheduler

Note: This method deletes all inactive computers from the directory without disabling them or asking for approval.

3. How to find the last logon time for all computers in a specific organizational unit (OU)?

Suppose the IT team needs to add new computers for incoming employees in the Finance department’s organizational unit (OU). So, before adding new devices, they decide to clean up the OU by removing inactive computers.

This process can be made faster and more efficient by retrieving the last logon data only for computers in the Finance OU. PowerShell makes this simple with a command that quickly lists the last logon details of all computers in a specific OU.

Check the last logon of all computers in a specific OU using PowerShell

  • Execute the PowerShell cmdlet below to quickly list the last logon timestamp of all computers in a specific OU. While execution, replace <OUDistinguishedName> with the OU's distinguished name.
  • Get-ADComputer -SearchBase “<OUDistinguishedName>” -Filter * -Properties Name, LastLogonDate | Select-Object Name, LastLogonDate | Sort-Object LastLogonDate
get-computers-last-logon-in-specific-ou

Note: If you’re not sure about the OU’s distinguished name, run the following cmdlet. 

Get-ADOrganizationalUnit -Filter * | Format-Table Name, DistinguishedName

Check computers’ last logon time in any OU in seconds and unlock deeper analysis with AdminDroid!

  • In AdminDroid’s All Active Directory Computers report, use the left-panel tree view to see all computers with their last logon timestamps specifically from a desired OU.
  • Need to take action? Select one or more computers, click More Action in the footer, choose the desired management task such as disable, delete, etc.
computers-last-logon-in-specific-ou-in-admindroid

Pro tip: Set custom alerts to get notified immediately when a computer’s last logon exceeds 30, 60, or any number of days you choose.

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!