Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / PowerShell

PowerShell Scripts to Apply Configuration Transformations for App.Config or Web.Config Files

5.00/5 (1 vote)
18 Aug 2015CPOL 20.7K  
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:

PowerShell
#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:

PowerShell
$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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)