Skip to content

Instantly share code, notes, and snippets.

@BenNeise
Last active December 16, 2015 13:29
Show Gist options
  • Save BenNeise/5442243 to your computer and use it in GitHub Desktop.
Save BenNeise/5442243 to your computer and use it in GitHub Desktop.
PowerShell function to search event logs of domain controllers for event ID 4740, and returns the time the event was logged (LockedTime), the user account SamAccountName (Account), the source computer (LockedFrom), and the current locked status (Locked)
Function Get-LockedADAccounts {
<#
.Synopsis
Gets lockout events from event logs on domain controllers
.Description
Searches event logs of domain controllers for event ID 4740, and returns the time the event was logged (LockedTime), the user account SamAccountName (Account), the source computer (LockedFrom), and the current locked status (Locked)
.Example
Needs no parameters, run like so
Get-LockedADAccounts
.Notes
Ben Neise 2013-23-04
#>
# Create an empty array for the results
$arrResults = @()
# Get a list of domain controllers
$objDomainContext = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext("Domain",(`
[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().Name)
)
$objDomainControllers = [System.DirectoryServices.ActiveDirectory.DomainController]::FindAll($objDomainContext)
# Iterate through the domain controllers
ForEach ($objDomainController in ($objDomainControllers | Sort-Object Name)) {
Write-Host "Getting lockout events on:" $objDomainController.Name
# Grab the events matching the account lockout ID
Try {
# Using SilentlyContinue to avoid displaying errors when no matching events are found)
$wmiEvents = @(Get-WinEvent -FilterHashTable @{LogName='Security'; Id=4740} -ComputerName $objDomainController.Name -ErrorAction SilentlyContinue)
}
Catch {
Write-Host "ERROR Can't get events, $_"
# Move onto the next DC
Continue
}
ForEach ($wmiEvent in $wmiEvents){
# Convert the event into an XML object
[xml]$XMLEvent = $wmiEvent.ToXML()
# Get the data from the XML, and append it to the WMI object
ForEach ($object in $XMLEvent.Event.EventData.Data){
$wmiEvent | Add-Member -Name ($object.Name) -MemberType NoteProperty -Value ($object."#text")
}
# Add the WMI object to the results array
$arrResults += $wmiEvent
}
}
Return ($arrResults | Sort-Object TimeCreated -Descending | Select-Object `
@{N="LockedTime";E={@($_.TimeCreated)}},`
@{N="Account";E={@($_.TargetUserName)}},`
@{N="LockedFrom";E={@($_.TargetDomainName)}},`
@{N="Locked";E={@((Get-QADUser $_.TargetUserName).AccountIsLockedOut)}} | Get-Unique -AsString
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment