PowerShell: Search for Failed Logins on Primary Domain Controller

# Quick Script to search for failed logins

$daysLimit=7
$userName="Bruce"
$todaysDate= Get-date
$pdc = (Get-ADDomain).PDCEmulator
#$allDCs = ((Get-ADForest).Domains | %{ Get-ADDomainController -Filter * -Server $_ }).Name

function getFailedLoginEvents{
param(
$dc,
$dayslimit,
$searchString
)

# Sanitize input
if($searchString[0] -ne "*"){$searchString="*"+$searchString}
if($searchString[$searchString.Length] -ne "*"){$searchString+="*"}

$results = Get-Eventlog security -Computer $pdc -InstanceId 4625 -After $todaysDate.AddDays(-$daysLimit) | `
Select TimeGenerated,ReplacementStrings|%{
if($_.ReplacementStrings[5] -like $searchString){
New-Object PSObject -Property @{
Source_Computer = $_.ReplacementStrings[13]
UserName = $_.ReplacementStrings[5]
IP_Address = $_.ReplacementStrings[19]
Date = $_.TimeGenerated
}
}
}
write-host $results;

if ($results){
return "$($results|ft -autosize|Out-String)";
}else{
return "$searchString not found.";
}
}

getFailedLoginEvents -dc $pdc -dayslimit $daysLimit -searchString $userName

Sample Result:

UserName     Source_Computer IP_Address  Date
-------- --------------- ---------- ----
Bruce.Leeeee DomainC-007 192.1.1.500 1/6/2020 1:03:33 AM
Bruce.Leeeee DomainC-007 192.1.1.500 1/6/2020 1:03:30 AM
Bruce.Leeeee DomainC-007 192.1.1.500 1/6/2020 1:01:24 AM
Bruce.Leeeee DomainC-007 192.1.1.500 1/6/2020 1:01:21 AM
Bruce.Leeeee DomainC-007 192.1.1.500 1/6/2020 1:00:10 AM

Leave a Reply

Your email address will not be published. Required fields are marked *