Query XML Data with Powershell

Introduction

XML files and data can be over encumbering and confusing to read. With the help of PowerShell this tutorial is going to help you learn how to query XML data and save valuable time. The syntax being used in today's tutorial is the XPath Syntax. This is the standard syntax used by PowerShell when performing queries against XML data.

The Commands

The interesting thing about XPath is that while it's still it's own language by itself, it's modeled after a common directory structure we see in our modern PC architecture. Below we can see an example of an XPath query string:

Example


    $path = "/note/heading"

Copy and Try it

Let's save some XML data to an XML variable to test our XPath string:

Example

$xml = [XML] "<note>

<to>Tove</to>

<from>Jani</from>

<heading>Reminder</heading>

<body>Don't forget me this weekend!</body>

</note>"

Copy and Try it

Great! Now we can target just the value of the heading property by using our $path variable and writing an XPath query:

Example

Select-Xml -XPath $query $xml | Select -Expand Node

Copy and Try it

Above, we are parsing the XML and then specifying which item we would like to abstract from the original data. The Select -Expand Node statement is essential in this use case scenario because it's returning the node (the value) of the heading property.