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)
# 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")
$root = $xml.get_DocumentElement();
# Add a new node
$node = $xml.createElement("mynewnode")
$subnode = $xml.createElement("add")
$attribute = $xml.CreateAttribute("url")
# Change existing node
$root.connectionStrings.add.connectionString = "My new connection string"
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 ./
Or from within Powershell
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