Friday, January 16, 2015

Querying XML with namespaces in PowerShell

Apparently it's ridiculously easy to parse XML in PowerShell once you have the right objects set up:

[xml] $xml = Get-Content .\DeploymentProfile.PRODUCTION.xml
$ns = new-object Xml.XmlNamespaceManager $xml.NameTable
$ns.AddNamespace('dns', '')
$xml.SelectNodes("//@dns:ServerHostName", $ns) | ForEach-Object { $_.Value } | sort | Get-Unique

In this example, I query a deployment configuration for attributes called "ServerHostName" within the XML namespace "". This was exceptionally useful today when I quickly needed to figure out what servers my system was using and send that information to others to configure those servers.

No comments: