Wednesday, February 2, 2011

Encrypting Web.Config part 2

Someone noted that my previous script for encrypting web.config files was missing out some applications and I discovered it was because they where at the root level and my script expected everything to running under a virtual directory.  This was correct for the development machines but on a production machine the site could be anywhere.

Working by file

To fix this I changed the script to simply find all the web.configs on a specific drive and do it that way.  It turned out to be easier than going via IIS and probably more accurate too.  There modified script is below:

$Dir = get-childitem G:\ -recurse
$List = $Dir | where {$_.name -eq "web.config"}

## Sections we want Hashed ###
$configSections = @('connectionStrings','appSettings')
## Command line for the encrypting system ###
$CmdLine = "C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis -pef "

foreach($file in $List)
{
    ### Process the directories ###
    write-Host "processing  -> " $file.fullname;
    foreach($section in $configSections)
    {
        $command = $CmdLine + $section + " " + $file.fullname + "' -prov 'RsaProtectedConfigurationProvider'";
        #invoke-expression -command $command | out-null
    }

}