Monday, October 17, 2011

Editing a web.config using PowerShell–changing a value method 2

A few days back I had a post about changing a value of an XML document in which I treated the returned item as and array and simply looped through the array.

I have had a reason to handle things a bit differently.

Lets consider the same bit of XML.


However, this time lets treat this like an object.

The first thing is to fetch the XML element in a way that PowerShell keeps it as an element.

I began last time by attempting to get the node using:


If I use the GetType() method PowerShell returns that it is an XmlElementList.  However, if I try to type dot then tab I cannot walk through the XML. 

This must be because the containing element is actually an XML element in its own right.

Okay I think, then I will get that element in the same way and I try:


Nothing.  What gives.  I must need to get at this a different way.  Using a little bit of object handling from another XML handling post I tried to treat it as an object.

$altAddr = $xml.GetElementsByTagName("routingPolicy") | where {$_.alternateAddress -match "on"}

If I use the GetType() method on this object I see that I have an XmlElement.  And I can modify its attributes with a simple dot notation.

$altAddr.alternateAddress = "off"

So, I achieved the same result as a few posts ago, but actually handling this as an object instead of as an array.


$routePolicy = @($xml.GetElementsByTagName("routingPolicy")) 
foreach ($e in $routePolicy) { 
     if ($e.alternateAddress -eq "off" ) { 
     $e.alternateAddress = "on" 


$altAddr = $xml.GetElementsByTagName("routingPolicy") | where {$_.alternateAddress -match "off"}
$altAddr.alternateAddress = "on"

And that After could probably be changed to a one liner.  I just find many one liners difficult to understand, and someone else will most likely have to figure out what my script does.

No comments: