PowerShell Script for Detecting Unauthorized Access Attempts
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.
### Step 1: Define the Time Range
First, we define the time range for which we want to check for unauthorized access attempts. In this example, we will check for the last 7 days.
“`powershell
$startDate = (Get-Date).AddDays(-7) $endDate = Get-Date
“`
### Step 2: Retrieve Security Log Entries
Next, we will retrieve the security log entries that contain failed login attempts recorded in the Event Log.
“`powershell
$failedLogins = Get-WinEvent -FilterHashtable @{ LogName = 'Security' Id = 4625 StartTime = $startDate EndTime = $endDate }
“`
### Step 3: Format and Display Results
Once we have the failed login attempts, we can format and display the results for easier reading.
“`powershell
$failedLogins | Select-Object TimeCreated, Message | Format-Table -AutoSize
“`
### Step 4: Export Results to CSV
For further analysis or record-keeping, we will export the results to a CSV file.
“`powershell
$outputPath = "FailedLoginAttempts.csv" $failedLogins | Select-Object TimeCreated, Message | Export-Csv -Path $outputPath -NoTypeInformation Write-Host "Failed login attempts exported to $outputPath."
“`
### Step 5: Alert for Unusual Activity
Lastly, we can add a simple alert mechanism to notify if the number of failed attempts exceeds a specified threshold, indicating potential unauthorized access attempts.
“`powershell
if ($failedLogins.Count -gt 10) { Write-Host "ALERT: More than 10 failed login attempts detected!" }
“`
This PowerShell script provides a straightforward way to monitor for unauthorized access attempts and helps administrators remain vigilant against potential security threats. Regular auditing of login events is essential for maintaining a secure environment.