Edit appSettings using PowerShell
Disclaimer: I am not a powershell expert and this script could do anything from update your appSettings to wipe your hard drive. You have been warned! :-)
Today I had to write a quick powershell script that would be used just after we deployed our application to the UAT environment. Basically we needed a quick way to update a few settings inside the applications configuration file for demonstration purposes to prove a concept to our client.
$configuration = "C:\App\app.config"
[xml]$xml = New-Object XML
$xml.Load($configuration)
foreach($n in $xml.selectnodes("/configuration/appSettings/add"))
{
switch($n.key)
{
"DeploymentDate" { $n.value = [DateTime]::Now.ToString("d/M/yyyy") }
"DateOfInitialization" { $n.value = [DateTime]::Now.AddDays(-2).ToString("d/M/yyyy") }
}
}
$xml.Save($configuration)
Firstly we need to set the location of the configuration file and then load the Xml into an Xml Document. Using XPath I then navigated down the xml document to the appSettings child nodes.
Using a switch statement whist looping over the add nodes I could then set new values for any of the configuration settings based on the key.
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="DeploymentDate" value="01/01/2010" />
<add key="DateOfInitialization" value="01/01/2010" />
</appSettings>
</configuration>
Pretty simple! I now love powershell as its perfect for getting things like this done quickly and easily.
Friday, 11th June, 2010 By Daniel Watson (powershell, appsettings)