# Get-RecentLogons.ps1 # Get recent successful and failed logon events for a user # Usage: .\Get-RecentLogons.ps1 -Username "DOMAIN\username" param( [Parameter(Mandatory=$true)] [string]$Username, [int]$Days = 30, [switch]$FailedOnly ) $StartDate = (Get-Date).AddDays(-$Days) Write-Host "Checking logon events for: $Username" -ForegroundColor Cyan Write-Host "Date range: $StartDate to $(Get-Date)" -ForegroundColor Cyan Write-Host "" # Security Event ID 4624 = Successful logon # Security Event ID 4625 = Failed logon # Security Event ID 4634 = Logoff $SuccessEvents = 4624 $FailedEvents = 4625 $FilterHashtable = @{ LogName = 'Security' StartTime = $StartDate } if ($FailedOnly) { $FilterHashtable.Id = $FailedEvents } else { $FilterHashtable.Id = $SuccessEvents, $FailedEvents } try { $Events = Get-WinEvent -FilterHashtable $FilterHashtable -ErrorAction Stop | Where-Object { $_.Message -imatch $Username } if (-not $Events) { Write-Host "No events found for $Username" -ForegroundColor Yellow exit 0 } $Results = @() foreach ($Event in $Events) { $EventID = $Event.Id $TimeCreated = $Event.TimeCreated # Parse XML for details $Xml = [xml]$Event.ToXml() $Data = $Xml.Event.EventData.Data $LogonType = ($Data | Where-Object { $_.Name -eq 'LogonType' }).'#text' $IpAddress = ($Data | Where-Object { $_.Name -eq 'IpAddress' }).'#text' $Workstation = ($Data | Where-Object { $_.Name -eq 'WorkstationName' }).'#text' $ProcessName = ($Data | Where-Object { $_.Name -eq 'ProcessName' }).'#text' $Results += [PSCustomObject]@{ Time = $TimeCreated EventID = $EventID Type = if ($EventID -eq 4624) { "SUCCESS" } else { "FAILED" } LogonType = $LogonType IpAddress = if ($IpAddress -eq "-") { "Local" } else { $IpAddress } Workstation = $Workstation Process = $ProcessName } } $Results | Sort-Object Time -Descending | Format-Table -AutoSize Write-Host "" Write-Host "Summary:" -ForegroundColor Green $SuccessCount = ($Results | Where-Object { $_.Type -eq "SUCCESS" }).Count $FailedCount = ($Results | Where-Object { $_.Type -eq "FAILED" }).Count Write-Host " Successful logons: $SuccessCount" Write-Host " Failed logons: $FailedCount" } catch { Write-Host "Error: $_" -ForegroundColor Red Write-Host "Make sure you're running as Administrator" -ForegroundColor Yellow }