← script library

PowerShell Script for Detecting Unauthorized Access Attempts

Security & AuditingJanuary 12, 2025

In this post, I will share a PowerShell script that helps in monitoring unauthorized access attempts on a Windows system. This script retrieves and analyzes the Security Event Log for failed login attempts, which can be crucial for identifying potential breaches and enhancing security measures.

powershell
$startDate = (Get-Date).AddDays(-7)
$endDate = Get-Date

$failedLogins = Get-WinEvent -FilterHashtable @{
    LogName = 'Security'
    Id = 4625
    StartTime = $startDate
    EndTime = $endDate
}

$failedLogins | Select-Object TimeCreated, Message | Format-Table -AutoSize

$outputPath = "FailedLoginAttempts.csv"
$failedLogins | Select-Object TimeCreated, Message | Export-Csv -Path $outputPath -NoTypeInformation
Write-Host "Failed login attempts exported to $outputPath."

if ($failedLogins.Count -gt 10) {
    Write-Host "ALERT: More than 10 failed login attempts detected!"
}

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.