Automate update of web.config with Microsoft Powershell

I have an ASP.NET web site project that I use for 5-10 web sites. Each has its own directory, setup in IIS and MySQL database, ie they work as independent web sites, only the code base is the same. For updates I have a setup with one Windows command file to copy out any file changes to the web site directories and another command file that updates the database with any database structure changes.

So far I have made any updates to the web.config files manually but today I finally figured out how to automate this too.

The Windows command tool Powershell has been around for a couple of years but I have not used it before. It was installed with Windows Update some time ago so it should be installed on your machine. To use it simply run powershell.exe from a command prompt. To exit, close the window or type exit.
Powershell can among other things run Powershell script files (file extension .ps1)

This script will show you how to add to and edit multiple web.config files (or any xml file)
[code lang=”xml”]
# Source: http://blog.tjitjing.com

# Array of files to make changes to, add as many as you like
$filesarray = @("c:\temp\web.config","c:\anotherfile.xml")

# Go thru all files
foreach ($filename in $filesarray)
{
# Get file + cast as xml
$xml = [[xml]](get-content $filename)

# Backup file before making changes
$backup = $filename + "-" + (get-date).tostring("yyyy-MM-dd-hh_mm_s")
$xml.Save($backup)

$root = $xml.get_DocumentElement();

# Add a new node
$node = $xml.createElement("mynewnode")
$root."system.web".appendChild($node)
$subnode = $xml.createElement("add")
$node.AppendChild($subnode)
$attribute = $xml.CreateAttribute("url")
$attribute.set_Value("http://blog.tjitjing.com")
$subnode.SetAttributeNode($attribute )

# Change existing node
$root.connectionStrings.add.connectionString = "My new connection string"

# Save
$xml.Save($filename)
}
[/code]

There are two caveats I ran in to when running my script:

1) You need to always give the path of the file, even if it is in your current directory. To run a file from current directory you need to wite ./
[code lang=”vb”]
C:\Temp>powershell.exe ./test.ps1
[/code]
Or from within Powershell
[code lang=”vb”]
PS C:\Temp>./test.ps1
[/code]

2) Powershells execution policy is by default set to Restricted. To avoid getting a message similar to “File C:\temp\test.ps1 cannot be loaded because the execution of scripts is disabled on this system.”, you need to run the command Set-ExecutionPolicy RemoteSigned from the powershell prompt.

Some useful links that helped me understand this and get it working:
Powershell on Microsoft Technet
Andy Schneider’s Blog about Windows PowerShell
Blog post by Dave Donaldson

1 comment

Leave a comment

Your email address will not be published. Required fields are marked *