Geeks With Blogs

News Google

Nick Harrison Blog<Nick>.Next()

I have recently been exploring the wonders of PowerShell. I also recently worked through some deployment / configuration issues and thought I would bring my newly acquired appreciation of PowerShell to the mix.

I had never given PowerShell a second thought. I really had no idea what it was or how it was used. This is very surprising given my perl background. Once I gave it a chance, I loved it.

One of the most exciting things about PowerShell is that unlike with regular scripting languages, you are not dealing with text. You are dealing with objects. More specifically, you are dealing with DotNet objects. So when you run a cmdlet like get-service, you don't get text back, you back a ServiceController. This means that you can easily start and stop services:

$service = get-service $serviceName

if ($service –ne $null)





This is very nice and so much easier being able to deal with objects.

With this in mind, how do we deal with the config files?

Instead of simply dealing with text, we can deal with an xml document. Powershell will actually "strongly type" the document, sort of. Consider a script like this:

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

$xml.Save($path+ ".old")

$runtime = $xml.configuration["runtime"]

if($runtime.gcServer -eq $null)


$gc = $xml.CreateElement("gcServer")

$gc.SetAttribute("enabled", "false")



$runtime.gcServer.enabled = "false";



This lovely little bit of magic will add the following configuration setting if it does not already exist




<gcServer enabled = "false"/>




There is a subtle point to note here. If there are no child elements to runtime to start with, $xml.configuration.runtime will be a string. If runtime already has elements, it will be an xml element. $xml.configuration["runtime"] will always be an xmlelements. This subtle distinction caused me some confusion initially and complicated writing my little script.


This type of script makes it easy to make a change to a deployment target, especially if you must make the same change to several servers.

It also makes it easy audit and verify that the server is in fact configured properly.


Turns out there are lots of uses for this new (at least new to me) tool for the ever growing tool box.


What are you doing with power shell?

Posted on Wednesday, May 25, 2011 5:00 PM | Back to top

Comments on this post: Updating the Machine.Config with PowerShell

comments powered by Disqus

Copyright © Nick Harrison | Powered by: