Identifying Locked-out Users with PowerShell
In this blog post, we'll dive into a script that helps administrators identify users who have been locked out of their accounts. The script, Get-LockedoutUsers.ps1, utilizes the Windows Event Log to detect and report on these instances.
Prerequisites
The Script
The script, Get-ADUserLockouts, is a cmdlet that allows you to identify users who have been locked out of their accounts. It does this by querying the Windows Event Log for events related to account lockout attempts.
function Get-ADUserLockouts {
[CmdletBinding(
DefaultParameterSetName = 'All'
)]
param (
[Parameter(
ValueFromPipeline = $true,
ParameterSetName = 'ByUser'
)]
#[Microsoft.ActiveDirectory.Management.ADUser]$Identity
#,
[datetime]$StartTime
,
[datetime]$EndTime
)
Begin{
$filterHt = @{
LogName = 'Security'
ID = 4740
}
if ($PSBoundParameters.ContainsKey('StartTime')){
$filterHt['StartTime'] = $StartTime
}
if ($PSBoundParameters.ContainsKey('EndTime')){
$filterHt['EndTime'] = $EndTime
}
$PDCEmulator = (Get-ADDomain).PDCEmulator
# Query the event log just once instead of for each user if using the pipeline
$events = Get-WinEvent -ComputerName $PDCEmulator -FilterHashtable $filterHt -MaxEvents 250
}
Process {
if ($PSCmdlet.ParameterSetName -eq 'ByUser'){
$user = Get-ADUser $Identity
# Filter the events
$output = $events | Where-Object {$_.Properties[0].Value -eq $user.SamAccountName}
} else {
$output = $events
}
foreach ($event in $output){
[pscustomobject]@{
UserName = $event.Properties[0].Value
CallerComputer = $event.Properties[1].Value
TimeStamp = $event.TimeCreated
}
}
}
End{}
}
How It Works
Begin Section
The script begins by defining a custom hashtable, $filterHt, that will be used to filter the event log. The hashtable is set up with the following properties:
Process Section
The script then enters the process section. This is where the event log query and filtering take place.
Key Code Snippets
foreach ($event in $output){
[pscustomobject]@{
UserName = $event.Properties[0].Value
CallerComputer = $event.Properties[1].Value
TimeStamp = $event.TimeCreated
}
}
Usage Examples
To use this script, simply dot-source it and pipe the output to the Out-GridView cmdlet. For example:
.\Get-LockedoutUsers.ps1 | Sort-object Username | Out-GridView -Title "Where are they locked out..?" -PassThru
Conclusion
In this blog post, we've explored a PowerShell script that helps administrators identify users who have been locked out of their accounts. The script uses the Windows Event Log to detect and report on these instances. By using parameters like StartTime and EndTime, you can further customize your query to focus on specific time periods or events.
You can find the full script, Get-LockedoutUsers.ps1, at the following GitHub