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', 'http://www.mycompany.com/Some/Namespace/Deployment/DeploymentProfiles.xsd')
$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 "http://www.mycompany.com/Some/Namespace/Deployment/DeploymentProfiles.xsd". 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:

Post a Comment