A million-event Security log will time out on you the moment you reach for Where-Object. The fix is to make the log do the filtering before a single record reaches PowerShell.
Every Windows administrator eventually writes the query that hangs. You want failed logons from the last day, you pipe Get-WinEvent -LogName Security into Where-Object, and the console sits there while PowerShell deserialises hundreds of thousands of events into objects just so it can throw almost all of them away. On a busy domain controller that is not slow, it is unusable. This post is about doing the opposite: pushing the filter down into the event log subsystem with -FilterHashtable and -FilterXPath, so you pull back the fifty events you wanted and nothing else. The examples are for PowerShell 7.4 on Windows Server 2022.
Why Where-Object is the wrong tool here
The difference is where the work happens. Get-WinEvent -LogName Security | Where-Object { $_.Id -eq 4625 } reads and materialises every event in the log as a rich .NET object, then evaluates your script block against each one in PowerShell. Get-WinEvent -FilterHashtable translates your criteria into a query that the Windows event log service applies at source, returning only matching records. On a small log the difference is invisible. On a Security log with a million events it is the difference between seconds and a session you have to Ctrl-C.
Free · 4 minutes
Is your engineering team shipping safely, or quietly accumulating risk?
Fourteen questions on how work gets from idea to production — cadence, testing, rollback, and the key-person risk in your delivery. Banded finding on screen, full sheet by email.
If your instinct is to reach for Get-EventLog instead, stop. That cmdlet is legacy, it only reaches the classic Application, System and Security logs, and it does not exist in PowerShell 7 at all — it was never ported from Windows PowerShell 5.1. Get-WinEvent is the supported path, it reads the modern Applications and Services logs as well as the classic ones, and it is the only one of the two that filters server-side.
The hashtable query that does the real work
The keys -FilterHashtable accepts are fixed: LogName, ProviderName, Path, Keywords, Id, Level, StartTime, EndTime, UserID and Data, plus any named data field the provider defines. Multiple keys are combined with logical AND, and Id and Level both accept arrays. Here is a targeted pull of failed-logon events (4625) from the last twenty-four hours:
$since = (Get-Date).AddDays(-1)
# Server-side filter: only 4625 events, only since yesterday.
$failures = Get-WinEvent -FilterHashtable @{
LogName = 'Security'
Id = 4625
StartTime = $since
} -ErrorAction SilentlyContinue
"{0} logon failures in the last 24h" -f $failures.Count
Two things in that snippet are not decoration. The -ErrorAction SilentlyContinue is there because when nothing matches, Get-WinEvent does not return an empty collection — it raises a non-terminating error, “No events were found that match the specified selection criteria.” In a scheduled script that noise will fill your logs or trip your error handling, so suppress it deliberately.
The second is what is not in the hashtable: there is no Level key. This is the trap that catches people moving filters from the System log to the Security log. Security audit events do not carry a meaningful severity Level — success and failure are encoded in Keywords, not Level. Add Level = 2 to a 4625 query expecting “errors” and you will get zero results and assume the log is empty. Event 4625 is a failed logon by definition, so filtering on the ID alone is both correct and sufficient.
Turning raw events into something you can read
A 4625 record carries the interesting detail — which account, from which host, over which logon type — inside its event data, not its message string. The reliable way to reach those fields is the event’s XML. Parse each record into a flat object and you have something you can sort, group or export:
$parsed = foreach ($event in $failures) {
$xml = [xml]$event.ToXml()
# Index the EventData fields by their Name attribute.
$data = @{}
foreach ($node in $xml.Event.EventData.Data) {
$data[$node.Name] = $node.'#text'
}
[pscustomobject]@{
Time = $event.TimeCreated
TargetUser = $data['TargetUserName']
LogonType = $data['LogonType']
Workstation = $data['WorkstationName']
SourceIp = $data['IpAddress']
SubStatus = $data['SubStatus']
}
}
# Which accounts are being hammered, and from where?
$parsed | Group-Object TargetUser |
Sort-Object Count -Descending |
Select-Object Count, Name -First 10
That grouping is the whole point of pulling logs at scale: not to read events one by one, but to see the shape of them. A single 4625 is noise. Two hundred against one service account from one IP address inside ten minutes is a brute-force attempt, and now it is one line of output rather than something buried in a log you never open. Getting that signal depends on the audit policy being switched on in the first place, which is part of any CIS-aligned Windows Server hardening baseline.
When you need XPath instead
The hashtable filters on whole events. When you need to filter on the contents of an event — a specific source IP, a particular target account — drop to -FilterXPath, which still runs server-side but can reach into the event data. This pulls only failures that came from a real network address, discarding the local - placeholder:
$xpath = "*[System[EventID=4625]] and *[EventData[Data[@Name='IpAddress']!='-']]"
Get-WinEvent -LogName Security -FilterXPath $xpath -MaxEvents 50 |
Select-Object TimeCreated, Id, Message
Use the hashtable by default; it is more readable and handles time ranges cleanly. Reach for XPath when the selection genuinely depends on a data field the hashtable cannot express.
Correlating across logs and exporting a report
Failed logons live in Security; service crashes live in System, raised by the Service Control Manager as events 7031 and 7034. Here the Level key is valid, because those are genuine Error-level events (Level = 2). This pulls a week of service failures and writes a tidy CSV a colleague can open without touching PowerShell:
$window = (Get-Date).AddDays(-7)
$crashes = Get-WinEvent -FilterHashtable @{
LogName = 'System'
ProviderName = 'Service Control Manager'
Id = 7031, 7034
Level = 2
StartTime = $window
} -ErrorAction SilentlyContinue |
Select-Object TimeCreated, Id,
@{ Name = 'Summary'; Expression = { ($_.Message -split "`n")[0] } }
$crashes | Export-Csv -Path .\service-crashes.csv -NoTypeInformation -Encoding utf8
"{0} service failures exported" -f $crashes.Count
The severity values are worth committing to memory, because they are how you filter the System and Application logs by importance: 1 is Critical, 2 Error, 3 Warning, 4 Information and 5 Verbose. A single query with Level = 1, 2 across the System log gives you every critical and error event of the day, which is a far better morning check than clicking through Event Viewer. If you are standing up a fresh box, wire this into the routine early — it pairs naturally with the rest of a baseline Windows Server 2022 setup, alongside configuring the firewall from PowerShell rather than the GUI.
The point of doing it this way
Server-side filtering is not a performance nicety; it is what makes event logs usable as evidence. A supervisor asking what happened during an incident, an auditor asking who failed to authenticate, a post-mortem asking which service died first — all of these are questions you answer by pulling a targeted slice out of a large log quickly and repeatably. Retention is the other half of that, and worth deciding on purpose rather than by default: how long you keep these logs, and where, is a governance question with real tension against the right to erasure. Get the filter right and the log stops being a place data goes to hide. That is the whole difference between having logs and being able to read them.
Build and rescue work
Hands-on delivery of this kind is handled by Sixteen Pillars Studio.
Free interactive tool
Website compliance checklist
What your site has to do, based on what it actually does
Answer as much or as little as you like — the list builds as you go. Nothing is stored against your name and no email is required.
Everything that applies
Ordered by what to do first: legal requirements you can close quickly, then larger pieces of work, then what is expected rather than required. Not exhaustive, and not a legal audit.
Dated PDF, yours to keep or circulate.
Can you trust the architecture you have?
Architecture diagrams rarely show the reality of how systems actually operate. An independent review establishes what is really there.