Skip to main content

How to Get the Last Logon Time of a User in Batch Script

Knowing exactly when a user last logged into a system is a fundamental requirement for IT auditing, security monitoring, and resource management. Whether you are identifying "Stale" accounts that haven't been touched in months or investigating a security incident to see if a compromised account was active during a specific window, gathering the "Last Logon" timestamp is the first step. While this data is stored in the local security database and Active Directory, you can extract it in seconds using a Batch script.

This guide explains how to pull this critical timestamp using the net user command.

Why Audit the Last Logon Time?

  • Security Forensics: Confirming if a specific user was active on a workstation during a reported "Breach Window."
  • Account Cleanup: Identifying and disabling accounts that haven't logged in for 90+ days to reduce the system's "Attack Surface."
  • License Optimization: Identifying users who haven't logged in recently to reclaim software licenses or hardware resources.
Local vs. Domain

The net user command targets the Local computer by default. In an enterprise environment, you must use the /domain flag to query the centralized Domain Controller for a user's network-wide logon history.

Method 1: Using Net User (Quick Lookup)

The simplest way to see the logon time is to run the basic user query and filter for the relevant field.

@echo off
setlocal

set /p "USN=Enter Username: "

if "%USN%"=="" (
echo [ERROR] No username entered.
pause
exit /b 1
)

echo [PROCESS] Retrieving metadata for "%USN%"...
echo.

net user "%USN%" 2>nul | findstr /i /c:"Last logon"

if %errorlevel% neq 0 (
echo [ERROR] User "%USN%" was not found in the local database.
echo [TIP] For domain accounts, use: net user "%USN%" /domain
)
pause

Method 2: Extracting the Timestamp into a Variable

To use the logon time in an automated reporting script (e.g., generating a daily "Active Users" log), you can use a FOR loop to isolate the date and time string.

@echo off
setlocal

set "TARGET=Administrator"

:: Verify the user exists
net user "%TARGET%" >nul 2>&1
if %errorlevel% neq 0 (
echo [ERROR] User "%TARGET%" not found.
pause
exit /b 1
)

echo [PROCESS] Auditing last activity for: %TARGET%

:: The "Last logon" line format is:
:: Last logon 1/15/2024 3:42:10 PM
:: Capture everything after "Last logon" by splitting on 'n' (end of "logon")
set "LOGON_TIME="
for /f "tokens=1,* delims=n" %%a in ('net user "%TARGET%" 2^>nul ^| findstr /c:"Last logon"') do (
for /f "tokens=*" %%t in ("%%b") do set "LOGON_TIME=%%t"
)

if defined LOGON_TIME (
echo.
echo [RESULT] Last recorded access: %LOGON_TIME%
) else (
echo [ERROR] Could not parse the logon timestamp.
)

echo.
pause

Creating a "Stale Account" Health Checker

This professional script checks a specific user and provides comprehensive account health information.

@echo off
setlocal EnableDelayedExpansion

echo ============================================================
echo User Activity ^& Stale Account Auditor
echo ============================================================

set /p "USN=Username to check: "

if "!USN!"=="" (
echo [ERROR] No username entered.
pause
exit /b 1
)

:: 1. Verify user exists
net user "!USN!" >nul 2>&1
if !errorlevel! neq 0 (
echo [ERROR] User "!USN!" does not exist on this machine.
echo [TIP] For domain accounts, use: net user "!USN!" /domain
pause
exit /b 1
)

:: 2. Display key account fields
echo.
echo [INFO] Account details for "!USN!":
echo -----------------------------------------
net user "!USN!" 2>nul | findstr /i /c:"Full name" /c:"Last logon" /c:"Account active" /c:"Password last set" /c:"Password expires"
echo -----------------------------------------

:: 3. Check for 'Never' logon
net user "!USN!" 2>nul | findstr /i /c:"Last logon" | findstr /i /c:"Never" >nul
if !errorlevel! equ 0 (
echo.
echo [ALERT] This account has NEVER been used!
echo [ACTION] Consider disabling with: net user "!USN!" /active:no
)

:: 4. Check for 'Never' password change
net user "!USN!" 2>nul | findstr /i /c:"Password last set" | findstr /i /c:"Never" >nul
if !errorlevel! equ 0 (
echo.
echo [ALERT] Password has NEVER been changed!
echo [ACTION] Force change at next logon: net user "!USN!" /logonpasswordchg:yes
)

echo ============================================================
pause

Common Pitfalls and How to Avoid Them

Administrative Rights

While standard users can often see their own last logon time, you must run your Batch script (and CMD) as an Administrator to query the metadata of other users or to pull reliable data from the domain.

Multi-Server Inconsistency

In a domain environment, the "Last logon" attribute is not replicated between Domain Controllers (DCs).

SEO and UX Tip

Advise your users that if they are in a corporate network, their script might return different times depending on which DC handled the logon. For a truly accurate network-wide date, it is recommended to query the LastLogonTimestamp attribute via PowerShell, which is replicated across all servers.

Best Practices for Activity Auditing

  1. Check Local vs. Domain: Users who log in while offline (e.g., on a laptop) might have a newer "Local" logon time than what the Domain Controller suggests. Compare both for a full picture.
  2. Combine with Password Date: A user who hasn't logged in for 6 months AND hasn't changed their password in a year is a high-security risk. Audit both fields simultaneously.
  3. Log to File: Use your script to loop through a list of usernames and save the results to a text file for a weekly "Cleanliness Audit."
Service Accounts

Note that some "Service Accounts" might log in thousands of times a day. Their "Last logon" time will always be "now," making them difficult to audit for abandonment using this method.

Conclusion

Getting the last logon time of a user via Batch script is a critical skill for any IT administrator focused on security and compliance. By programmatically extracting these timestamps, you can move beyond manual guesswork and make data-driven decisions about account lifecycle management and system access. This professional approach to system identification ensures that your organization's user accounts are active, monitored, and secure, providing a clear and automated view of your infrastructure's health across the entire Windows network.