Editing Web.Config Files with PowerShell

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
   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"
   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)
  12: #save a backup copy
  13: $xml.Save($backup)
  15: #this was the trick I had been looking for
  16: $root = $xml.get_DocumentElement();
  18: #Change the Connection String. Add really means "replace"
  19: $root.connectionStrings.add.connectionString = $connectionString
  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.


2 Responses to “Editing Web.Config Files with PowerShell”

  1. Jenna Says:

    That is a good tip particularly to those fresh
    to the blogosphere. Brief but very precise info… Thank
    you for sharing this one. A must read article!

  2. 用PowerShell实现web.config中连接字符串的替换 | Tesla9527 Says:

    […] 参考资料:https://getpowershell.wordpress.com/2008/07/29/editing-webconfig-files-with-powershell/ […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: