Using Powershell to Replace Config Settings in Lab Management

LabManagement
6861

So you’ve got your virtual environment running and you’re deploying your application using the Lab Default Workflow. Only, you have a config file and you need to update a connection string or something in the config file for automated tests to run properly.

Now if you’re deploying websites, for goodness sake use WebDeploy  and the Web.Config transforms within Visual Studio to configure your web.configs as part of the WebDeploy packaging. This is by far the easiest way to deploy web applications into lab environments.

However, if you’ve got some other configs that need to be twiddled as part of the deployment, then create a PowerShell script to do your replacements.

Given an XML that looks like this:

<configuration>
<
settings LogTraceInfo="False" KeepConnectionAlive="True">
<
sql server="dbserver" database="Live" />
settings>
configuration>

Let’s say you want to replace the database property. Here’s the PS to do this:


######################################################################################
#
# Usage: ReplaceDatabaseInConfig.ps1 -configPath "path to config" -database "new database name"
#
######################################################################################
param($configPath, $database)

Write-Host "Replacing database name in config file..."

# Get the content of the config file and cast it to XML
$xml = [xml](get-content $configPath)
$root = $xml.get_DocumentElement();

# change the db name
$root.settings.sql.database = $database

#save
$xml.Save($configPath)

Write-Host "Done!"

###########################################################################

Check this script into Source Control – make sure that you get it into your drop folder somehow (add it to a solution and mark it’s action to “Copy Always” or something along those lines).


Then it’s a simple matter of executing the script as part of your deployment. If you set the working directory to the folder where your deployment copies the script, then you can invoke it as follows:


cmd /c powershell .\ReplaceDatabaseInConfig.ps1 -configPath "AppCustom.config" -database "Live"


In your build log, you’ll see the following:


image


Happy testing!