Problem overview
Failed login attempts can indicate unauthorized access attempts, brute-force attacks, misconfigured credentials, or forgotten passwords. Without real-time monitoring, organizations risk security breaches, account lockouts, or undetected threats. This script helps IT teams proactively detect and respond to suspicious authentication failures before they escalate into serious security incidents.
<#
This resource is provided as a convenience for Level users. We cannot
guarantee it will work in all environments. Please test before deploying
to your production environment. We welcome contributions to our community
library
# Level Library
# https://level.io/library/script-windows-failed-login-any-user
#>
$TimeFrame = (Get-Date).AddHours(-1)
# Get failed logon attempts in the last hour
$FailedLogins = Get-WinEvent -FilterHashtable @{
LogName = 'Security'
Id = 4625
StartTime = $TimeFrame
} -ErrorAction SilentlyContinue
if ($FailedLogins.Count -gt 0) {
$AlertMessage = "ALERT: Multiple failed login attempts detected in the last hour!`n"
# Extract usernames from the events
$FailedLogins | ForEach-Object {
$Xml = [xml]$_.ToXml()
$Account = $Xml.Event.EventData.Data | Where-Object { $_.Name -eq "TargetUserName" } | Select-Object -ExpandProperty "#text"
if ($Account) {
$AlertMessage += " - Failed login for account: $Account`n"
}
}
Write-Host $AlertMessage.Trim()
exit 1
} else {
Write-Host "No failed login attempts detected."
exit 0
}
This script scans Windows Event Logs for failed login attempts (Event ID 4625) in the past hour and extracts the usernames associated with these failures. If any failed logins are detected, it outputs an alert listing the affected accounts. By integrating this script with a script-based monitor in Level, IT teams can receive real-time alerts whenever failed login attempts occur, allowing them to investigate and take appropriate action.
Use cases
- Detect brute-force attacks attempting to gain unauthorized access.
- Monitor failed login attempts across all user accounts.
- Identify misconfigured accounts causing repeated login failures.
- Enhance security monitoring and compliance auditing.
- Notify IT teams of abnormal authentication activity in real time.
Recommendations
- Pair with a script-based monitor in Level to generate alerts for failed login attempts automatically.
- Test before deploying in a production environment to ensure accurate detection.
- Review login failure patterns to identify potential security threats.
- Adjust log retention policies to store authentication failure records for forensic analysis.
- Integrate with automated responses to temporarily lock accounts after multiple failed attempts.