29. July 2008
Andy Schneider
A couple days ago, a colleague of mine (who is a recent PowerShell convert) asked me if there was some cool way in PowerShell to update a web.config file based on the particular environment that the app was being deployed to (dev, test, or production)
I went in to this knowing config files are just XML files and I also knew that PowerShell can do some pretty cool work with XML and I figured there must be a way.
I found a great article called Deployment made simple using Powershell by Omar Al Zabir up on Code Project.
He has a script that does a number of things, but what I was particular interested in was changing the database connection string in a web.config file.
Luckily, Omar had the answer.
I tweaked it a bit and came up with the following:
1: #Code to update a connection string on a web.config file –yes this can be used to change a lot more stuff too J
2:
3: #Set the Connection String and the path to web.config (or any config file for that matter)
4: $connectionString = "Data Source=old-db;Initial Catalog=mydb;Integrated Security=True;User Instance=True"
5: $webConfigPath = "C:\Inetpub\wwwroot\myapp\web.config"
6: $currentDate = (get-date).tostring("mm_dd_yyyy-hh_mm_s") # month_day_year - hours_mins_seconds
7: $backup = $webConfigPath + "_$currentDate"
8:
9: # Get the content of the config file and cast it to XML and save a backup copy labeled .bak followed by the date
10: $xml = [xml](get-content $webConfigPath)
11:
12: #save a backup copy
13: $xml.Save($backup)
14:
15: #this was the trick I had been looking for
16: $root = $xml.get_DocumentElement();
17:
18: #Change the Connection String. Add really means "replace"
19: $root.connectionStrings.add.connectionString = $connectionString
20:
21: # Save it
22: $xml.Save($webConfigPath)
The one thing I added was the backup copy by saving the current file with the current date and time appended to the end of the file name.
So next time you are tempted to edit a config file with notepad, open up the shell and take a whack at it.