Preparing web.config for Deployment using PowerShell

After you build your Web Project in Visual Studio, it would be nice to automatically process the developer’s web.config to remove any sensitive information, such as login credentials, and other information that sits in the config file for debugging or testing purposes.

As described in the previous entry, the build batch generates a compiled web application, and renames the web.config to web.publish.config, to avoid accidentally overwriting an existing web.config during an upgrade.

This PowerShell script opens the web.publish.config, replaces the connection string with a place holder, and removes two config sections (the XML manipulations shown are for illustration only):

$config = "c:\path-to\published\app\web.publish.config"

[xml]$cfg = Get-Content $config

"$config loaded"

$node = $cfg.SelectSingleNode("//connectionStrings/add[@name='default']")
$node.connectionString = "Data Source=LOCALHOST;Initial Catalog=THECATALOG;Persist Security Info=True;User ID=USERNAME;password=PASSWORD"

$node = $cfg.SelectSingleNode("//appSettings")
if ($node) { $node.RemoveAll() }

$node = $cfg.SelectSingleNode("//system.web/pages/controls")
if ($node) { $node.RemoveAll() }

$sr = New-Object System.IO.StreamWriter $config
$cfg.Save($sr)
$sr.Close()

"$config saved"

The script loads the web.config, performs some XML operations (notice the inline addressing of the connectionString attribute), and saves the XML document to its original name.

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 )

Facebook photo

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

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.