Monday 20 July 2015

Edit C# config file with PowerShell

So today we changed the organization name, too long to explain and all the external apps needed to have their app.config changed to reflect this change. This was across several environments so I thought it would probably be quicker to write a quick script to do it.

The script works for multiple files because they are on subfolders of a common folder, e.g.

Mycompany --> My App 1
                   --> My App 2
                   --> My App 3

It will of course work from say, c:, if you have your apps in different places but it might take a while to run. It will not work if they are in different drives though.

Here's the script:

param ($path, $keyname, $value)

if (-not($Path))
{
 write-host "Path is a mandatory parameter"
 break;
}

if (-not($keyname))
{
 write-host "KeyName is a mandatory parameter"
 break;
}

if (-not($value))
{
 write-host "value is a mandatory parameter"
 break;
}

$configfiles = ls -Path $path -Recurse -Include *config

foreach ($config in $configfiles)
{
 $doc = (Get-Content $config) -as [Xml]
 $obj = $doc.configuration.appSettings.add | where {$_.Key -eq $keyname}
 $obj.value = $value
 $doc.save($config)
}
Assuming the script has been named ChangeConfigFile.ps1, it can be invoked like this:
 ChangeConfigFile.ps1 -path "c:\program files\Apps\" -keyname "Organization" -value "NewOrg"

No comments:

Post a Comment