Modifying Web.Config with PowerShell

It’s still amazing to me some of the traffic I get from Stack Overflow for posts I wrote years ago. Below is another one about using PowerShell to flip the debug mode in a web.config file, which is weird to think about now because of the advent of config transform files.

Begin wayback machine…

Original post date: 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.

Here’s a web.config file that contains only the <compilation> node with debug=”true”:

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:

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 ;-)

… end wayback machine.

Featured Image: All rights reserved by dougchase

Leave a Reply

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