- 1 year ago
PowerShell, weird behaviour of Get-WinEvent -FilterHashTable ID and arrays
The Get-WinEvent
cmdlet in PowerShell is used to retrieve events from event logs on Windows. When using the -FilterHashTable
parameter to filter events by specific properties, you may encounter some unexpected behavior when filtering by ID
and arrays.
The -FilterHashTable
parameter expects a hashtable with key-value pairs representing the properties to filter on. However, there is a specific behavior related to using arrays with the ID
key in the hashtable.
When filtering by ID
, the cmdlet will match events that have any of the specified event IDs if you pass an array of IDs. This behavior is different from other properties where the cmdlet expects an exact match for each element in the array.
Here's an example to illustrate the behavior:
Let's say you want to filter events with event IDs 1001, 1002, and 1003:
powershell# Filtering by ID with an array
$ids = @(1001, 1002, 1003)
$events = Get-WinEvent -LogName "Application" -FilterHashTable @{ID = $ids}
In this example, the cmdlet will return events with any of the specified event IDs (1001, 1002, or 1003). It doesn't require an exact match for each element in the array. This behavior is specific to the ID
key in the hashtable when using the -FilterHashTable
parameter.
If you want to filter by multiple specific event IDs, the above approach is correct. However, if you want to filter events with a specific ID only, you can directly pass the ID value without using an array:
powershell# Filtering by a single ID
$eventId = 1001
$events = Get-WinEvent -LogName "Application" -FilterHashTable @{ID = $eventId}
In this case, the cmdlet will return events with the exact event ID 1001.
To summarize, when using Get-WinEvent
with the -FilterHashTable
parameter to filter events by ID
and arrays, remember that it will match events with any of the specified event IDs in the array, not requiring an exact match for each element in the array. For filtering by a specific event ID, directly pass the ID value without using an array.