Quick tip on XML / XPath filtering of Event Logs

I’ve seen several examples of XML / XPath filtering of event logs, some of them from Microsoft, which look like this:

*[EventData[Data[@Name='SubjectUserName'] and (Data='test9')]] 

This sort of works, but you need to understand what it really means. It looks for a Data node under EventData which has a Name attribute of SubjectUserName, then it looks for a Data node under EventData whose text data is equal to ‘test9’. What’s important here is that the Data nodes identified by these two conditions don’t actually have to be the same. Most of the time, this won’t be a problem, but let’s assume that you want to look for events where the SubjectUserName is NOT equal to test9:

*[EventData[Data[@Name='SubjectUserName'] and (Data!='test9')]] 

This command would most likely return all events with a SubjectUserName data field, even the ones that were equal to ‘test9’. Again, breaking down the logic here, you’re saying “Look for events that have a Data node named SubjectUserName, and a Data node whose value is not equal to test9.” It’s not actually saying “look for Data nodes named SubjectUserName that are also not equal to ‘test9′”, which is what the intent here should be. To fix these XPath queries, do this instead:

*[EventData[Data[@Name='SubjectUserName'] != 'test9']] 

This can be useful in PowerShell if you want to use Get-WinEvent’s FilterXPath or FilterXML parameters, and also just for defining filters and custom views in the Event Viewer (including specifying which events to include in Event Forwarding.) They all use the same XML / XPath syntax.


About Dave Wyatt

Microsoft MVP (PowerShell), IT professional.
This entry was posted in PowerShell and tagged , , . Bookmark the permalink.

2 Responses to Quick tip on XML / XPath filtering of Event Logs

  1. Dave says:

    Thanks, great explanation on XML filtering


  2. Ryan says:

    Very helpful. Thank you!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s