Active Directory: Audit users' lock out events with Powershell (Part I)

It can be useful to have count on the locked out domain users, to investigate recurring users or simply for statistics.
In Windows 2008 lock out events are registered in 'Security' eventviewer with id 4740.
With the cmdlet get-winevent we can get those events (what usuer, when and from where) and save them in a logfile for later analysis.

This script is prepared to execute from task scheduler several times a day.

$strdate=get-date -format MMMM_yyyy
$logfile="LockedoutEvents_$strdate.txt"
#connect with DC's eventviewers
$DCs="SERVERDC03","SERVERDC04","SERVERDC05"
Foreach ($DC in $DCs)
{
write-host "Getting events from $DC..."
$lockoutevents=Get-WinEvent -ComputerName $DC -FilterHashtable @{LogName='Security';Id=4740} -erroraction silentlycontinue
if ($lockoutevents -ne $null)
{
 foreach ($event in $lockoutevents)
 {
 $who=$Event.Properties[0].Value 
 $when=get-date($Event.TimeCreated) -uformat "%d/%m/%Y %H:%M:%S"
 $where=$Event.Properties[1].Value
 out-file $logfile -input "$who $when $where" -append
 }#end foreach events
}#end if events not null
}#end foreach DCs

#clean the log of repeat events
$cleanlogfile=get-content($logfile)|select -unique
$cleanlogfile|out-file $logfile
Because of cyclic Security events, I've scheduled this task to execute every hour from the PDC emulator. With last two lines of the script I avoid logging repeated events.

Have a look to the post: Audit users' lock out events with Powershell (Part II) to see an easy way of parsing the logs.

Comments