Automation guides, explanations and reader checklists on whilenetworking.com

PowerShell Guide: Building a Scheduled Job that Parses Windows Event Logs to Auto-Remediate Failed Login Attempts

In enterprise environments, brute-force attacks and credential stuffing are persistent threats. While modern Identity and Access Management (IAM) solutions…

In enterprise environments, brute-force attacks and credential stuffing are persistent threats. While modern Identity and Access Management (IAM) solutions often handle lockouts automatically, understanding the underlying mechanisms provides IT professionals with robust, scriptable fallbacks. This guide demonstrates how to build a Windows Scheduled Task that monitors Event Logs for failed login attempts and triggers an auto-remediation workflow using PowerShell. By combining Get-WinEvent with conditional logic, you can create a resilient security layer that operates independently of third-party vendors.

Understanding the Security Scenario and Prerequisites

Before writing code, it is essential to understand the data source and the remediation target. Windows records authentication failures in the Security log (Event ID 4625). A typical scenario involves an attacker guessing passwords for a specific user account. If three distinct failed attempts occur within a short window, the system should automatically lock that account or notify an administrator.

Prerequisites:
* Windows Server or Windows 10/11 Pro/Enterprise: The schtasks utility and full PowerShell module set are required.
* Administrator Privileges: You must run the script as Administrator to access the Security log and modify user account properties.
* Local Account Knowledge: You need to know the username or a filterable attribute of the accounts you wish to protect. In this example, we will target a generic “TestUser” but explain how to generalize it later.
* Lab Environment: Always test these scripts in an isolated lab (e.g., a dedicated VM) before deploying to production. Never run unverified remediation scripts on a live network without rigorous testing.

Parsing Event Logs with Get-WinEvent

The core of this automation is reading the Security log efficiently. PowerShell’s Get-WinEvent cmdlet is optimized for this purpose. We will filter specifically for Event ID 4625, which indicates an account failed to log on.

We must extract specific fields: the timestamp, the username (TargetUserName), and the failure code. The FilterXPath parameter allows us to query XML within the event record directly.

# Define a function to retrieve recent failed login events
function Get-FailedLoginEvents {
    param(
        [int]$TimeoutMinutes = 5, # Check logs from the last 5 minutes
        [string]$EventId = 4625   # Event ID for Failed Logon
    )

    try {
        $events = Get-WinEvent -LogName "Security" -FilterXPath "*[System[EventID=$EventId]]" -MaxEvents 100 -ErrorAction Stop

        if ($events.Count -eq 0) {
            return @()
        }

        # Extract relevant data into a clean object array
        $failedLogins = foreach ($event in $events) {
            [PSCustomObject]@{
                Timestamp   = $event.TimeCreated
                Username    = $event.Message | Select-String -Pattern 'TargetAccountName\s*=\s*(\S+)' | ForEach-Object { $_.Matches.Groups[1].Value }
                FailureCode = $event.Message | Select-String -Pattern 'Status\s*=\s*(\d+)' | ForEach-Object { $_.Matches.Groups[1].Value }
            }
        }

        return $failedLogins
    }
    catch {
        Write-Warning "Failed to retrieve events: $_"
        return @()
    }
}

What this does: The function queries the Security log for the last 5 minutes. It uses regex (Select-String) to parse the raw event message string, which is often faster than parsing the XML directly for simple text extraction. This creates a list of users who have failed to log in recently.

Building the Remediation Logic and Thresholds

Once we have the list of failed attempts, we must apply business logic. A single failure is usually benign; five failures might indicate a script error or user confusion; ten failures suggest an attack. We will implement a threshold check. If a specific user appears three times in our parsed list within the timeout window, we trigger remediation.

# Configuration Variables
$Threshold = 3
$LockoutDurationHours = 24

# Get failed logins from the previous function (simulated here for clarity)
# In a real script, you would call: $failedLogins = Get-FailedLoginEvents -TimeoutMinutes 5

# Group by username and count occurrences
$violators = $failedLogins | Group-Object Username | Where-Object { $_.Count -ge $Threshold }

foreach ($group in $violators) {
    $targetUser = $group.Name
    Write-Host "User '$targetUser' has exceeded the threshold of failed attempts." -ForegroundColor Red

    # Remediation Step: Disable the account via Active Directory or Local Security Policy
    # Note: On a domain controller, you need RSAT tools. On a local machine, use Set-LocalUser.

    try {
        Set-LocalUser -Name $targetUser -AccountDisabled $true
        Write-Host "Successfully disabled account '$targetUser'." -ForegroundColor Green
    }
    catch {
        Write-Error "Could not disable user '$targetUser'. Error: $_"
    }
}

Key Considerations:
* Generalization: The example above targets any user. In a production environment, you should restrict this to specific service accounts or high-value user groups to avoid accidentally locking out legitimate users during configuration errors.
* Notification: A robust workflow includes sending an email or creating a ticket in ServiceNow/Jira upon lockout. This is omitted here to keep the scope focused on the core automation but is recommended for real-world use.

Scheduling the Job with Task Scheduler

A script runs only when executed. To make it automatic, we must configure Windows Task Scheduler. This ensures the check runs every 15 minutes or upon system startup, depending on your risk tolerance.

  1. Open Task Scheduler (taskschd.msc) as Administrator.
  2. Right-click Task Scheduler Library > Create Task… (Do not use “Create Basic Task” for complex scripts).
  3. General Tab: Select “Run with highest privileges.” Check “Run whether user is logged on or not.”
  4. Triggers Tab: New trigger -> Begin: “On startup” or “Daily”. Repeat every: “15 minutes”.
  5. Actions Tab: New -> Action: “Start a program”.
    • Program/script: powershell.exe
    • Arguments: -ExecutionPolicy Bypass -File "C:\Scripts\MonitorLogins.ps1"
    • Start in (optional): C:\Scripts

Why Highest Privileges? The script needs to write back to the system (disable accounts) and read protected logs. Running as a standard user will result in access denied errors when attempting to modify security settings.

Verification Steps and Common Errors

Deploying automation introduces new failure modes. You must verify that your job is working without causing collateral damage.

Verification Checklist:
1. Dry Run: Temporarily change the script logic to only Write-Host the intended actions instead of executing them. Run the scheduled task manually via the UI and check the output in the console.
2. Log Review: Check the Task Scheduler logs for the specific task. Look for “Last Result” codes (0 indicates success). Non-zero codes indicate errors that need investigation.
3. Event Validation: Ensure the Get-WinEvent call isn’t timing out or hitting rate limits on the Security log. If the log is fragmented, performance may degrade.

Common Errors and Fixes:
* Error: “Access Denied” when disabling a user.
* Fix: Ensure the task is running with “Run with highest privileges.”
* Error: “The process cannot access the file because it is being used by another process.”
* Fix: This often happens if the script tries to read and write to the same locked registry key or log file. Add a Start-Sleep -Seconds 5 between heavy operations if necessary, though usually, it indicates a locking conflict in your code logic.
* Error: Regex parsing fails on empty messages.
* Fix: Wrap your string extraction in if ($_.Matches) checks to prevent null reference exceptions when an event record lacks the expected text pattern.

Student Practice Task and Industry Application

For Students:
Create a virtual machine with two user accounts: “Admin” and “TestUser”. Write a PowerShell script that parses the Security log of your VM. Modify the script so that it only locks “TestUser” after three failures but logs every attempt to a text file (C:\Logs\LoginAttempts.log). Schedule this task to run every 10 minutes. Manually trigger four failed logins for “TestUser” and observe the automatic lockout in Task Manager.

Industry Application:
In a large enterprise, this logic is often integrated into a larger SIEM (Security Information and Event Management) correlation engine. However, for smaller organizations or branch offices without expensive SIEM licenses, a local PowerShell scheduled job serves as an excellent “zero-cost” defense-in-depth measure. It reduces the Mean Time to Respond (MTTR) from hours (human investigation) to minutes (automated reaction).

Conclusion

Building a scheduled job that parses Windows Event Logs and auto-remediates failed logins is a practical application of PowerShell automation. It requires careful attention to event filtering, threshold logic, and privilege management. By following the steps above—parsing logs with Get-WinEvent, implementing conditional lockout logic, and configuring Task Scheduler—you can significantly harden your endpoint’s security posture against brute-force attacks. Remember that while this script provides a strong safety net, it should be part of a broader security strategy including multi-factor authentication (MFA) and regular patching. Always test in a lab environment before applying these changes to production systems.

Educational-use notice: This tutorial is for learning and controlled lab use only. Test carefully, use backups, and obtain authorization before making changes. Do not run unfamiliar commands on production systems. We accept no responsibility for misuse, damage, data loss, or production issues.