Getting Values from XML Using PowerShell

Working on a recent project I was tasked with maintaining VMware host configuration via XML files. The goal was to have a central location to modify the settings of a host (DNS, vmkernel interfaces, vswitch config, port groups) without having to update each host by hand. This lead me down the path of using PowerShell with XML files as the configuration source.

Below is the sample of my XML file.

What we have here is 3 port groups (Management Network, VM Network, Web Network) with a VLAN, Virtual Switch, and Cluster defined. The entire file sits inside the “config” tags. Each portgroup lives inside the “portgroups” tag, and the values for each portgroup live inside the individual “portgroup” tags.

Below is a sample command to get values from an XML file. We pass the file location as a variable and then we store all those values inside another variable to make working with the values easier.

$xmlFile = "C:\Scripts\sample.xml"
$xmlConfig = [System.Xml.XmlDocument](Get-Content $xmlFile)

And once we type in $xmlConfig into Powershell we can see that it is pulling in the data from our XML file.

We can see the “config” section, but how do we dig deeper? Type in $xmlconfig.config and let’s look at the output

Now we can see the “portgroups” section. Let’s go deeper and see what’s inside of that by typing the following:


Nice! Now we can see all the portgroups we have defined. In order to get detail on each of these, we can type $xmlconfig.config.portgroups.portgroup and we’ll get a list of all the portgroups and all their values.

Now let’s say we are only concerned about retrieving values from one of those portgroups. We can add a Where clause to find only the Portgroups that exist on vSwitch1 as an example with the following command:

$xmlconfig.config.portgroups.portgroup | Where {$_.virtualswitch -eq "vSwitch1"}

Grabbing values out of an XML file is pretty straightforward. In the next post we’ll talk about how to add information to an XML file.

Getting Values from XML Using PowerShell

2 thoughts on “Getting Values from XML Using PowerShell

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s