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.