How to iterate through XML in Powershell?

PowerShell has built-in XML and XPath functions.
You can use the Select-Xml cmdlet with an XPath query to select nodes from XML object and then
.Node.’#text’ to access node value.

[xml]$xml = Get-Content $serviceStatePath
$nodes = Select-Xml "//Object[Property/@Name="ServiceState" and Property='Running']/Property[@Name="DisplayName"]" $xml
$nodes | ForEach-Object {$_.Node.'#text'}

Or shorter

[xml]$xml = Get-Content $serviceStatePath
Select-Xml "//Object[Property/@Name="ServiceState" and Property='Running']/Property[@Name="DisplayName"]" $xml |
  % {$_.Node.'#text'}

Leave a Comment