Geeks With Blogs

@neh123us
  • neh123us T4 sould be your outsourcing strategy https://t.co/1ZceCUKWKE T4 - The Insource Code Monkey about 322 days ago
  • neh123us Had a need for Dynamic Views in MVC today. Wanted to use a Partial view on two different views with different ViewModels about 370 days ago

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)

{

$service.Stop()

}

 

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.AppendChild($gc)

}

$runtime.gcServer.enabled = "false";

$xml.Save($path)

 

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

 

<configuration>

<runtime>

<gcServer enabled = "false"/>

</runtime>

</configuration

 

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: GeeksWithBlogs.net | Join free