Offer Offer

News We Recently Launched AD Migrator and AD Reporter.

How to Check Active Directory User Login History With PowerShell

  author
Written By Mohit Jha
Anuraag Singh
Approved By Anuraag Singh  
Published On September 19th, 2024
Reading Time 13 Minutes Reading

Every once in a while, IT admins need to check in on the user activity going on inside the Active Directory. For that, they usually start by searching “How to check active directory user login history?”. This is especially true for novice administrators who have just taken over the responsibility of managing an AD. Due to their inexperience, they might think that the task is simple with the availability of PowerShell scripts.

However, that’s exactly where the problems begin. The commands you find online are not verified and are designed for a foreign system. So to help you view and check the user logon data, we have compiled the various sources within this writeup. Therefore, you no longer need to spend countless hours scouring the net. This also causes problems further down the line when admins look for answers to what is Active Directory and related questions.

Moreover, apart from the usual PowerShell code, here you also get to see a professional utility in action. Let’s first start by deconstructing the exact needs of an admin when they search for a query like this.

Table of Contents

Why do Admins Want to Get AD User Login History At All?

Admins like yourself may start finding user login data for one of the following reasons:

  • Comply with the industry regulations: Depending on the industry, admins may have to conduct a mandatory user activity checkup. This process is part of the regulatory process and must be done at a fixed frequency.
  • Perform a security check of the Active Directory: Looking at the login data of individuals admins can figure out whether or not an entry request was genuine. Moreover, if someone is trying a forced entry it is often characterized by multiple attempts from a remote location.
  • Predecessor to an employee evaluation report: Login information is an important parameter through which companies can check the productivity of their employees. Which makes it easier to help those who are falling behind their required quota.
  • Move Active Directory Objects across domains: Migrating Active Directory has become ever more common due to the increase in mergers and acquisitions. Having a list of active users helps admins fast-track this transfer which otherwise is a major project on its own.

Even though this list is not exhaustive, it covers the majority of the reasons that administrators have in their minds. So now as the reasons are out of the way let’s get straight to the PowerShell script you should use.

How to Check User Login History in Active Directory Using PowerShell? Explained

Before using the script, test it and apply modifications.

$users = Get-ADUser -Filter * -Properties LastLogonDate, LastLogonTimestamp, LastLogoff

# Create an array to store the results
$results = @()

foreach ($user in $users) {
$result = [PSCustomObject]@{
Username = $user.SamAccountName
LastLogon = $user.LastLogonDate
LastLogonTimestamp = [DateTime]::FromFileTime($user.LastLogonTimestamp)
LastLogoff = $user.LastLogoff
}
$results += $result
}

# Display the results in a table format
$results | Format-Table -AutoSize

Don’t copy-paste directly; it may not work as intended. Do the following instead.

  • Save the script as a Get-ADUserloginHistoryInteractive.ps1 file.
  • Open a PowerShell window with administrator privileges.
  • Navigate to the directory where you saved the script.
  • Run the script

Check User Login History in Active Directory Using PowerShell

Moreover, despite the best efforts, these commands are not foolproof. Let’s see why this is the case.

Problems With PowerShell Command to Get User Login Details

Scripts tend to break down during edge cases. Like a situation where your Active Directory is brand new and thus has no users. This is a known situation; there might be other unknown cases that can cause the script to behave abruptly.

The PowerShell method may not give you the exact information on how to check user login history in Active Directory in one try. Making it a suboptimal way of answering how to check Active Directory user login history for any admin. Moreover, you have to continuously reiterate the command structure. Taking up a lot of time and effort for even a basic task like user login information retrieval.

Most scripts, like the one presented here, are designed for a general audience. As the AD is highly customizable, it is rarely the case that you can find a solution right away. It is recommended that as the admin you find the user location inside the Active Directory first. This is to see if or not you are checking the right domain.

Moreover, if you don’t possess the right skill set, these commands may do irreplaceable damage to the AD.

All in all, PowerShell commands don’t seem like the right way to attempt data accumulation in AD, especially if you have little to no knowledge. Not to worry, as we have just the right solution for you

Answer How to Check Active Directory User Login History by Skipping the PowerShell Script

The SysTools Active Directory Reporting Software is the best way to get a complete user login list in no time. It eliminates the need to troubleshoot complex PowerShell scripts altogether. This is done via a unique and simple-to-understand user interface. This, when combined with its fast and secure algorithms, gives administrators a considerable advantage over traditional methods.

Download Now Purchase Now

Multi-domain addition, CSV file output, and Date range filters are just some of the extra features that admins get from this utility. To use the tool flow, follow the instructions provided ahead.

Steps to Get AD User Login History in an Automated Manner

Step 1. Open the Tool and type the default “administrator” in both the User ID and password tabs. You can reset it via the tool settings later.
Type administrator

Step 2. After activation, click on the “REGISTER DOMAIN CONTROLLER” button on the center of your screen.
Register Domain Controller button

Step 3. Fill in the Domain Friendly Name and IP address in the space provided and hit Save & Continue.
register domain controller

Step 4. The tool automatically takes you to the Domain details page, where you have to enter the Actual Admin credentials and validate them. This pushes you closer to the answer of how to check Active Directory user login history than ever before.
Save Credentials

Step 5. Click on the Report tab to open up the reporting options. Choose the one that helps you answer how to find user login history in Active Directory. That would be the Login sub-category inside the Users section.
Report tab multiple options

Step 6. The tool presents the filtering menu, where the options you chose previously are pre-selected.  You can toggle the User Workload and Login Category options and find the exact AD user data you wish to see.
User

Step 7.  Pick a specific duration there is a list of premade timelines starting from 5 days up to a year. You can select the custom option to fine-tune your results.
preset time intervals

Step 8. Click on the Preview button to generate a tabular representation of user login details.
Preview

Step 9. Expand the Download Report button and select CSV to fetch your Active Directory User Login Report.
Download CSV

Step 10. Confirm by hitting the Download option in the popup.
Download button

Step 11. A Save as screen opens from where you can select the location to put the report. Press Save.
save CSV report

Step 12. Open the CSV file on any visualizer and check the results.
View CSV

Enable Event Viewer

Part 1:

Before we can track user history in Event Viewer We must enable the logon/logoff events.

  • Press Windows + R and type “gpmc.msc” to launch the “Group Policy Management” console.
    type “gpmc.msc” to launch the “Group Policy Management”
  • To build a new audit for the entire domain right-click on it and select “Create a GPO in this domain, and Link it here…”.
    Create a GPO in this domain, and Link it here…
  • In the new GPO window add a name.
    Make a new GPO to check user login history in Active Directory
  • Right-click on the new GPO. Then select the Edit option.
    select the Edit option
  • Follow this path “Computer Configuration” > “Policies” > “Windows Settings” > “Security Settings” > “Local Policies” > “Audit Policy”.
  • On the Right Pane, you will find the “Audit logon events” policy click on it twice. This opens up the property windows.
  • Mark the box next to “Success” and “Failure” then press “OK”.
  • Repeat for “Audit Account Logon Events” policy as well.
  • Close the GPME.
    Audit Account Logon Events

Part 2:

Now add this GPO to the AD objects for that.

  • Reopen the Group Policy Management Console and pick the new GPO
  • Go to the “Security Filtering” tab in the right panel, and click “Add”.

“Security Filtering” tab

  • Doing this opens the “Select User, Computer or Group” dialog box.
  • Enter “Everyone”. Click on “Check Names” and validate. After that click “OK” to first add it and then apply it to all objects.
    Enter “Everyone” to check login history in Active Directory for all users
  • Close the “Group Policy Management Console”.
  • Force the update with the help of gpupdate /force command.
    use gpupdate /force command

How to Check User Login History in Active Directory With Event Viewer Portal?

Open Event Viewer > Toggle Windows Logs > Select Security and use the Find option to search for these Event IDs:

Event ID 4624 – Successful account logon: If you see this code then it means that login was successful on the local computer. You can see the logon type and username involved along with the rest of the network information. Admins should check this event regularly to see who enters into the AD as this information is not present on the Domain Controllers.
event 4624 to check user login history in Active Directory

Event ID 4625 – Failed account logon: As the name suggests admins can get the AD user login history of a failed login attempt with its cause e.g., bad password. While you are at it, check the user password expiration date, too. Admins look for this Event ID during the security audits.
event 4625 to check user login history in Active Directory

Event ID 4634 – Account logoff: Whenever this code appears on the Event Viewer it indicates that a user login session came to an end and that they logged off from the Active Directory. This event cannot trigger for a user who didn’t record a 4624 ID earlier.
event 4634 to check user login history in Active Directory

Event ID 4647 – User-initiated logoff: This Event ID is like the regular logoff (4634) with one key difference being that the logoff was interactive. This can also be triggered in case of a logoff from a Remote interactive session.

Event ID 4648 – User Logon With Explicit Credentials: It is the type of Event ID that is associated whenever a process attempts to log in to a user account by utilizing its explicit credentials. It is a common occurrence in the case of batch configuration and/or RUNAS command.
event 4648 to check user login history in Active Directory

All Event IDs in the form of 46XX are pulled from the workstations directly.

Here is a small flow chart that indicates a user login event and its various outcomes.

Flow Chart to Form a Manual Active Directory User Logon/Logoff Report via PowerShell

Flow chart to Check User Login History in Active Directory

First up ensure that the user account exists, no login attempt successful or otherwise can be made if there is no user account to begin with.

Once the existence of a user account is confirmed the next step is to see if the user has attempted a login or not. There are instances where not a single login event is made from the user side, so no event ID is generated that’s why admins need to filter out those Dormant accounts to avoid confusion.

Next, the actual process begins when a user tries to log in. Even the most basic form of AD security requires credential validation. So user needs to put in the given credentials or continue with the old one.

After this one of two outcomes might happen either the credentials are validated or they are not.

In the case of the former (valid credentials) a secondary check is made to ensure that the user account is not expired or disabled from the admin end.

The enabled users get access to all AD resources.

However, if during the system checks, any of the credentials (username, password, or both) mismatch from the database then the user cannot log in.

Depending on the group policy users may have 3 – 5 attempts to re-enter the correct credentials after which they automatically lockout (temporarily or permanently). The user requires admin intervention from here on.

From this, we form the following PowerShell script.

# Define variables
$userName = "username" # Replace with the actual username to check
$maxLoginAttempts = 5 # Replace with the actual maximum allowed login attempts

# Function to check if a user account exists
function Check-UserAccountExists {
param ($userName)
$user = Get-ADUser -Identity $userName -ErrorAction SilentlyContinue
if ($null -ne $user) {
return $true
}
return $false
}

# Function to check if the user has attempted to log in
function Check-UserLoginAttempts {
param ($userName)
$logonEvents = Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4624} | Where-Object { $_.Properties[5].Value -eq $userName }
if ($logonEvents.Count -gt 0) {
return $true
}
return $false
}

# Function to validate user credentials
function Validate-Credentials {
param ($userName, $password)
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ($userName, $securePassword)
try {
$null = (New-Object System.DirectoryServices.DirectoryEntry("", $cred.Username, $cred.GetNetworkCredential().Password)).nativeObject
return $true
}
catch {
return $false
}
}

# Function to check if the account is expired or disabled
function Check-AccountStatus {
param ($userName)
$user = Get-ADUser -Identity $userName -Properties AccountExpirationDate, Enabled
if ($user.Enabled -and ($null -eq $user.AccountExpirationDate -or $user.AccountExpirationDate -gt (Get-Date))) {
return $true
}
return $false
}

# Function to handle login attempts and lockout policy
function Handle-LoginAttempts {
param ($userName, $password)
$attempts = 0
while ($attempts -lt $maxLoginAttempts) {
if (Validate-Credentials -userName $userName -password $password) {
if (Check-AccountStatus -userName $userName) {
Write-Host "Access granted to AD resources."
return
} else {
Write-Host "Account is expired or disabled."
return
}
} else {
$attempts++
Write-Host "Invalid credentials. Attempt $attempts of $maxLoginAttempts."
}
}
Write-Host "Account locked out. Please contact admin for intervention."
}

# Main script logic
if (Check-UserAccountExists -userName $userName) {
if (Check-UserLoginAttempts -userName $userName) {
$password = Read-Host -AsSecureString "Enter Password"
Handle-LoginAttempts -userName $userName -password $password
} else {
Write-Host "No login attempts detected. Account is dormant."
}
} else {
Write-Host "User account does not exist."
}

Conclusion

In this writeup, we have given users the answer for how to check Active Directory user login history. Moreover, users can view logon data reports with or without PowerShell, choosing the approach that suits them best. All we can say is that, from the evidence we have listed here, it is safe to say that the tool is easier and faster. It outperforms the traditional script-based approach and so experts recommend it too.

Frequently Asked Questions on AD User Login Tracking

What can be the reasons for an invisible user login history in our Active Directory?

  • Checking in the wrong domain
  • Users didn’t log in
  • Event Viewer Issues

The PowerShell command shows a user login event but the user was on leave how is it possible?
IT admins approach login and logoff events in AD PowerShell modules with skepticism, as they are infamous for potential inaccuracies. Moreover, noise from parallelly running network sessions can also result in many false positives.
We can hope for a partial remedy by constructing centralized logs in the built-in Windows Event Forwarding. This can correlate with AD data to add insights you receive from the professional tool which can help admins to reduce false positive login events by a significant margin.

Why am I unable to check user logoff data in the Active Directory?
Every user must be logged in at the moment. Moreover, it’s a known issue that AD is somewhat unreliable in tracking when exactly the users log in. As its primary focus is on monitoring login

Is there a way to check user login history in Active Directory from command line?
Yes you can use the query

net user /domain

To list every user on the domain then use

net user %username% /domain | findstr /C:"Last logon"

check user login history in Active Directory from command line

Replace the %username% variable with the user name whose login data you require. This method seems simple however, the catch is that you can only see when the user logs in but not when they log out.

  author

By Mohit Jha

Mohit is a Microsoft Certified expert known for his cloud migration, cyber security, and digital forensics expertise. He specializes in Microsoft 365, Exchange Server, and Azure AD migration, ensuring seamless transitions for organizations worldwide. His multifaceted role as a meticulous tech writer, diligent researcher, and astute editor underscores his commitment to delivering cutting-edge digital forensics and cloud migration strategies.