Wednesday, June 3, 2015

PowerShell scripts to apply configuration transformations for App.Config or Web.Config files

By default, Visual Studio provides configuration transformation for Web.config file. As well as, App.Config files can be transformed using a "SlowCheetah" or similar add-ons available in Visual Studio Gallary.

But there may be the cases where the configuration transformation is not supported by project template in Visual Studio, or in case, during TFS build, if you would want to create configuration transformation files for all of the release configurations, and not particular to a single release configuration. 

Through this, the same deployment package created during TFS build can be deployed on different environments.

Following is the PowerShell function I have created to achieve this -

#Apply config transformation
function applyConfigTransformation($src,$xdt,$dst)
{
Add-Type -Path "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v12.0\Web\Microsoft.Web.XmlTransform.dll"

try 
{
Write-Host 'applyConfigTransformation - Called'
Write-Host $src
$doc = New-Object Microsoft.Web.XmlTransform.XmlTransformableDocument
$doc.PreserveWhiteSpace = $true
Write-Host 'applyConfigTransformation - Load Called'
$doc.Load($src)
Write-Host 'applyConfigTransformation - Load completed'

$trn = New-Object Microsoft.Web.XmlTransform.XmlTransformation($xdt)

if ($trn.Apply($doc))
{
Write-Host 'applyConfigTransformation - $trn.Apply called'
$doc.Save($dst)
Write-Output "Output file: $dst"
Write-Host 'applyConfigTransformation - $trn.Apply completed'
}
else
{
throw "Transformation terminated with status False"
}
}
catch
{
Write-Output $Error[0].Exception

}

Following is how this function can be called -

$src = "C:Projects\MyWebApp\web.config"
$xdt = "C:Projects\MyWebApp\Configs\web.PreProduction.config"
$dst = "C:Projects\MyWebApp\web.PreProduction.config"
applyConfigTransformation $src $xdt $dst

No comments:

Post a Comment

Thanks for visiting my blog.
However, if this helped you in any way, please take a moment to write a comment.

Thanks
Nirman