Filtering XML Child Elements in PowerShell

Recently I was working with some XML documents along the lines of the following. Each set of data had some common elements, Name and Description and other elements based around a pattern, Filepathx.

[xml]

[/xml]

I needed to check the path for any of these that were present in each dataset. Working with XML files in PowerShell is pretty straightforward. For instance to work with the above file you could start with:


$xml = \[ xml \](Get-Content .\\Test.xml)

and drill down into the data with


$xml.dataset.data

but how would you pick out those columns based on the header name of FilePathx, that could not be predicted and would vary each time both in the number of them and the x element?

I can return and filter the property names with Get-Member, but how to then access the child elements?


$xml.dataset.data | Get-Member -MemberType Property | where {$\_.name -like 'FilePath\*'}

Turns out that the object we are working with System.Xml.XmlElement has a ChildNodes property, but you don’t see that by piping the object into Get-Member, only if you view the MSDN page. However, if you use the Force parameter then you will see a get_childnodes method which will give you a hint that a ChildNodes property exists, but PowerShell is not exposing it via Get-Member.


$xml.dataset.data | Get-Member -Force

So now we can filter the data how we need to:


$xml.dataset.data | select -ExpandProperty childnodes | where {$\_.name -like 'FilePath\*'}

and if I pick out a suitable property I can carry out the necessary test of whether the file exists.


$xml.dataset.data | select -ExpandProperty childnodes | where {$\_.name -like 'FilePath\*'} | select -ExpandProperty InnerText | Test-Path