PowerShell: Filter by User when Querying the Security Event Log with Get-WinEvent and the FilterHashTable Parameter
I recently ran across something interesting that I thought I would share. The help for the
FilterHashTable
parameter of Get-WinEvent
says that you can filter by UserID using an Active
Directory user account's SID or domain account name:
1help Get-WinEvent -Parameter filterhashtable
Notice that the help also says the data key can be used for unnamed fields in classic event logs. I often hear the question wanting to know what the valid key pairs are for the hash table. As you can see, they're listed in the help.
First, we'll start out by determining which domain controller in our Active Directory domain holds
the PDC emulator FSMO role since information for all account lockouts that occur in a domain are
stored in the security event log of the PDC emulator. Don't over-complicate locating the PDC
emulator. If you have the Active Directory PowerShell module installed which installs as part of
RSAT (Remote Server Administration Tools), PDCEmulator is one of the properties that is returned by
default by the Get-ADDomain
cmdlet:
1Get-ADDomain | Select-Object -Property pdcemulator
Now, we'll query the security event log on the PDC emulator for all account lockout events:
1Get-WinEvent -ComputerName dc01 -FilterHashtable @{logname='security';id=4740}
We're looking for lockout events for a user with the userid of 'afuller' so let's grab the SID for his user account:
1Get-ADUser -Identity afuller
As the help stated, we'll add the userid key and the user's SID to our hash table:
1Get-WinEvent -ComputerName dc01 -FilterHashtable @{logname='security';id=4740;userid='S-1-5-21-3309960685-2715817658-858357121-1407'}
As shown in the previous set of results, a message is received stating no events exist that match the specified criteria.
Usually, this is where most people will simply pipe to Where-Object
because they can't figure out
how to filter left by user. The UserID key doesn't work as expected in this scenario, so an
alternate method is to use the data key in the hash table instead of the userid key and specify the
user's SID as the value:
1Get-WinEvent -ComputerName dc01 -FilterHashtable @{logname='security';id=4740;data='S-1-5-21-3309960685-2715817658-858357121-1407'}
You can also use the data key to filter by userid:
1Get-WinEvent -ComputerName dc01 -FilterHashtable @{logname='security';id=4740;data='afuller'}
Now we can add a couple of custom properties to determine what device is causing the account lockout:
1Get-WinEvent -ComputerName dc01 -FilterHashtable @{logname='security';id=4740;data='afuller'} |
2Select-Object -Property timecreated,
3@{label='username';expression={$_.properties[0].value}},
4@{label='computername';expression={$_.properties[1].value}}
The moral of the story here is there are hidden gems in the built in help so don't underestimate its content.
µ