Skip to content

Instantly share code, notes, and snippets.

@jpbruckler
Created August 9, 2023 22:16
Show Gist options
  • Save jpbruckler/3025833421aba61ce159cd24811a6cc9 to your computer and use it in GitHub Desktop.
Save jpbruckler/3025833421aba61ce159cd24811a6cc9 to your computer and use it in GitHub Desktop.
Function to provide an XPath filter suitable for use in Azure Monitor Data Collection Rules.
function New-DcrXPathFilter {
<#
.SYNOPSIS
Generates an XPath filter based on specified Event IDs and a log name.
.DESCRIPTION
The New-DcrXPathFilter function takes an array of Event IDs, a log name,
and an optional operator to create an XPath filter. This filter can be
used to query specific events from the Windows Event Log.
.PARAMETER EventIds
An array of integers representing the Event IDs to filter. This parameter
is mandatory and must contain at least one valid Event ID.
.PARAMETER LogName
The name of the Windows Event Log to filter. This parameter is mandatory.
.PARAMETER Operator
Specifies the logical operator to use between the Event IDs in the filter.
Accepted values are 'or' and 'and'. The default value is 'or'.
.EXAMPLE
$EventIds = 4624, 4625
$LogName = 'Security'
$filter = New-DcrXPathFilter -EventIds $EventIds -LogName $LogName -Operator 'or'
$filter will contain the XPath filter to search for events 4624 or 4625 in the Security log.
.INPUTS
int[], string, string
.OUTPUTS
string
.NOTES
If more than 20 Event IDs are specified, the function will call itself
recursively to build the filter.
#>
param(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[int[]] $EventIds,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string] $LogName,
[ValidateSet('or', 'and')]
[string] $Operator = 'or'
)
# Check log name
$LogName = (Get-WinEvent -ListLog * -ea SilentlyContinue | Where-Object LogName -eq $LogName ).LogName
if (-not $LogName) {
throw 'Log name not found. Try running the following: (Get-WinEvent -ListLog * | Where-Object LogName -like "*$LogName*").LogName'
}
if ($EventIds.Count -eq 1) {
return "$LogName!*[System[EventID=${EventIds[0]}]]"
} elseif ($EventIds.Count -gt 20) {
$output = @()
$output += New-DcrXPathFilter -EventIds $EventIds[0..19] -LogName $LogName -Operator $Operator
$output += New-DcrXPathFilter -EventIds $EventIds[20..($EventIds.Count - 1)] -LogName $LogName -Operator $Operator
return $output
} else {
$sb = [System.Text.StringBuilder]::new()
$null = $sb.Append(('{0}!*[System[(' -f $LogName))
$limit = $EventIds.Count - 1
for ($i = 0; $i -lt $limit; $i++) {
$null = $sb.Append("EventID={$EventIds[$i]} $Operator ")
}
# Append the last EventID without the 'or'
$null = $sb.Append("EventID={$EventIds[-1]}")
$null = $sb.Append(')]]')
return $sb.ToString()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment