| Modifying Web.config with PowerShell |
| Thursday, December 11 2008 |
|
For all you .NET-ers, you know how during your development cycle you set debug="true" in web.config, and then when you get ready to release your application you have to remember to switch it to be debug="false"? And how many times have you had to re-deploy your web.config all because you simply forgot to do that? Yea, me too, but I've figured out a way to automate this using PowerShell, and not only that, I've discovered how to do it in only five lines of code.
For completeness, here's a web.config file that contains only the <compilation> node with debug="true":
<configuration> <system.web> <compilation debug="true" /> </system.web> </configuration>
To change debug="true" to debug="false", I started down the path of using the typical XPath stuff to get the <compilation> node and its attributes. But in doing so, somewhere along the way I stumbled across an article (which I've since lost the link and now can't find) that showed a shortened, more terse way of making the change. You can see it in line 4 of this block of script:
1: $webConfig = "C:\Inetpub\Wwwroot\MyApp\web.config"
2: $doc = new-object System.Xml.XmlDocument
3: $doc.Load($webConfig)
4: $doc.get_DocumentElement()."system.web".compilation.debug = "false"
5: $doc.Save($webConfig)
I assume the ability to do this has been around for quite awhile and I'm just now discovering it, but that makes things *so* much nicer than having to use XPath with XmlNodes and XmlAttributes. Using get_DocumentElement() to get the root node of the XML document and then simple dot notation to traverse the child nodes and attributes is a thing of beauty.
Just one word of caution: be sure to call the Save() method on the XML document object. I forgot to do that and spent an hour trying to figure out why my changes weren't being saved. Ouch is right ;-)
