PowerShell v2 Adding AppSettings Elements to Web config

As a part of a web site process I needed to add an appSettings key/value pair to some web.config files.  I found several scripts that offered insight:

  • http://social.technet.microsoft.com/Forums/uk/winserverpowershell/thread/9e644edd-2e62-4d01-84e0-95fdd67b2055 
  • http://get-powershell.com/post/2008/07/29/Editing-WebConfig-Files-with-PowerShell.aspx 
  • http://blogs.msdn.com/b/ssehgal/archive/2009/05/30/automating-config-file-changes-part-4-adding-a-new-element-to-an-xml-file.aspx 

This one, however, was the one I went with:
  • http://geekswithblogs.net/nharrison/archive/2011/05/25/updating-the-machine.config--with-powershell.aspx 
In it I found this snippet:
$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 gave me something to work with.  In my case, I wanted to touch all of my machine level ASP.NET web.config files so I came up with this:

$webconfigs = @(
"C:WindowsMicrosoft.NETFrameworkv2.0.50727CONFIGweb.config",
"C:WindowsMicrosoft.NETFrameworkv4.0.30319Configweb.config"
)

foreach($webconfig in $webconfigs)
{
[String] $timestamp = (Get-Date -Format yyyyMMddhhmmss)

Write-Output "Making backup of $webconfig."
if(-not(Test-Path "$webconfig.$timestamp"))
{
Write-Output "Backup created."
$xml.Save("$webconfig.$timestamp")
}

Write-Output "Getting content of $webconfig."
$xml = [xml](get-content($webconfig))

Write-Output "Checking for appsettings in $webconfig."
$appSettings = $xml.configuration["appSettings"]
if($appSettings -eq $null)
{
$as = $xml.CreateElement("appSettings")
$as.SetAttribute("aspnet:SomeKey", "SomeValue")
$appSettings.AppendChild($as)
}

Write-Output "Saving $webconfig."
$xml.Save($webconfig)
}
The script is pretty straightforward:

  • create an array of web.configs
  • iterate collection
  • make a backup (if it doesnt exist)
  • read the file
  • check for appSettings key
  • if none exist add the key
  • save the new config
As I write this it makes me realize I need to include some logic to add the element in case the appSettings exist, but, thats for another post.

Related Posts by Categories

0 comments:

Post a Comment