← script library

User Logon History Exporter

Security & AuditingDecember 27, 2024

This PowerShell script provides a convenient way to export user logon history from a Windows system. System administrators often need to track user activity for security and compliance reasons, and this script simplifies that process. By integrating with ServerEngine, administrators can maintain better oversight of user access patterns, helping to ensure security and optimize resource usage. The script generates a CSV file with logon times and user details.

powershell
param (
    [string]$outputFilePath = "C:\UserLogonHistory.csv"
)
# Get the logon events from the Windows Event Log
$logonEvents = Get-WinEvent -LogName Security | Where-Object { $_.Id -eq 4624 }
# Create an array to store logon details
$logonDetails = @()
foreach ($event in $logonEvents) {
    # Extract details from each event
    $timeCreated = $event.TimeCreated
    $username = $event.Properties[5].Value  # The username is usually the 6th property
    $logonDetails += [PSCustomObject]@{
        TimeCreated = $timeCreated
        Username = $username
    }
}
# Export the logon details to a CSV file
$logonDetails | Export-Csv -Path $outputFilePath -NoTypeInformation
Write-Output "User logon history has been exported to $outputFilePath."

Run it across your fleet

This script runs as-is on a single host. Paste it into ServerEngine to schedule it, run it on a whole server group in parallel, and keep the credentials out of the file — see the scripts documentation and the credential store.

Ready when you are.

Try ServerEngine free for 7 days.