How to filter the Windows Security event log by SID?

Solution 1:

Use the -FilterXPath option instead!

In the following example, I've saved all events from the Security log on my machine to seclog.evtx on the Desktop and search for events with SubjectUserSid S-1-5-18 (LOCAL SYSTEM):

$events = Get-WinEvent -Path "$HOME\Desktop\seclog.evtx" -FilterXPath '*[EventData[Data[@Name="SubjectUserSid"] = "S-1-5-18"]]'

In a script, I would probably opt for a splatting table to make the statement a bit more readable (here limited to the last 10 events):

$seclogSplat = @{
    'Path'        = "$HOME\Desktop\seclog.evtx"
    'FilterXPath' = '*[EventData[Data[@Name="SubjectUserSid"] = "S-1-5-18"]]'
    'MaxEvents'   = 10
}
$events = Get-WinEvent @seclogSplat

You can specify multiple non-exclusive criteria with or:

*[EventData[Data[@Name="SubjectUserSid"] = "S-1-5-18" or Data[@Name="SubjectUserSid"] = "S-1-0-0"]]

Solution 2:

I don't know of any built in way to find out if a specific UserID exists.
However, you can just match the content of the message to find your SiD, as it should be unique:

$events = get-winevent -logname security -path "Archive-Security-2015-04-14-02-13-02-299.evtx" | where {$_.message -match 'S-1-5-21-220523388-838170752-839522115-yyyy'}

There are also some cleaner ways using XML filtering.
But personally I haven't had a need for them yet, and content matching the message has been sufficient so far.