Thursday, May 5, 2011

PowerShell and XML–bah to overly simplistic examples

Okay, I have been manipulating XML with PowerShell on and off for over a year now.  And I will tell you, all the examples that you find on the internet are way too simplistic.

I have yet to get a piece of XML out of code that is very simple, neat and tidy.

Working with CIM interfaces and XML application configuration files I frequently find my XML muddied up with array strings within tags.

Oh my.  These arrays within an XML Element reek havoc on the nice simple XML parsing that PowerShell does (and assumes).

Or, worse yet, the XML is filled with namespaces and therefore you cannot simply [xml] (cast it to XML) and deal with it.

Say for example that I have a web config file that I want to change, and it is written in XML.  first I have to get the file:

$file = get-childitem -path "IIS:\Sites\Default Web Site\App\Settings\web.config"

Then get the content of the config file and cast it to XML:

$xml = [xml](get-content $file)

Within this file are tags and settings that are actually arrays of settings within tags.  Or they are dictionaries (but they don’t return that way).

In the XML might look like this:

<AppThings allowSomething="on" showBar="off">
  <client />
  <someAppPolicy setting="off" />
  <someOtherAppPolicy enableFoo="off" />

To modify one of these array settings I simply treat it as an array an modify the proper setting.

$somePolicy = @($xml.GetElementsByTagName("someAppPolicy"))

foreach ($e in $somePolicy) {
    if ($e.setting -eq "off" ) {
    $e.setting = "on"

At the end you just have to remember to write the XML back to the file:


No comments: