PowerShell 2.0: One Cmdlet at a Time #21 Select-XML

Continuing the series looking at new cmdlets available in PowerShell 2.0. This time we look at the Select-XML cmdlet.

What can I do with it?

Search for text in an XML document using an XPath query.

Example:

Example.xml

ExampleXML

From the file Example.XML search with the XPath query /shop/food

Select-XML -Path example.xml -XPath "/shop/food"

Select-XML

You’ll notice this hasn’t returned any actual data from the XML file rather details of the search carried out and two matches. This is because Select-XML returns a SelectXMLInfo Object, illustrated below by piping the same command to Get-Member.

Select-XMLGet-Member

To retrieve the results pipe the SelectXMLInfo object through to Select-Object and use the ExpandProperty parameter.

Select-XML -Path example.xml -XPath "/shop/food"
 | Select-Object -ExpandProperty Node

Select-XMLSelect-Object

How could I have done this in PowerShell 1.0?

You could have used the Get-Content cmdlet to read the Example.xml file in as text, converted it to an XML type using [XML] and then used the SelectNodes method to retrieve the data.

[xml]$xml = (Get-Content example.xml)
$xml.SelectNodes("/shop/food")

Select-XMLv1

1000 things 1% better!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>