Config transforms via powershell

We had another quick powershell challenge in the office – we are trying to squeeze every second out of our build server, both for our CI build and for our automated deployments (faster feedback = good).

We were spending 3-4 minutes on the UAT build running an msbuild step. This job had a dependency on the CI build, and was essentially building the same version of the code. The reason for this was to transform the configuration files.

This script is a work in progress, but runs in seconds and transforms the config files in place throughout the entire solution (we still need to come back and copy the config files to the output directories).

    [string] $foldername,
    [string] $configuration
function XmlDocTransform($xml, $xdt)
    if (!$xml -or !(Test-Path -path $xml -PathType Leaf)) {
        throw "File not found. $xml";
    if (!$xdt -or !(Test-Path -path $xdt -PathType Leaf)) {
        throw "File not found. $xdt";
    Add-Type -LiteralPath "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v14.0\Web\Microsoft.Web.XmlTransform.dll"
    $xmldoc = New-Object Microsoft.Web.XmlTransform.XmlTransformableDocument;
    $xmldoc.PreserveWhitespace = $true
    $transf = New-Object Microsoft.Web.XmlTransform.XmlTransformation($xdt);
    if ($transf.Apply($xmldoc) -eq $false)
        throw "Transformation failed."
$configs = Get-ChildItem $foldername -Recurse | where {-not $_.PsIsContainer -and  $_.Directory -notlike '*\bin*' -and $_.Directory -notlike '*\obj*' } | where {$ -like "*.$configuration.config" }
foreach($config in $configs) {
    $baseConfig = $config -replace "$configuration.", "";
    Write-Host "Transforming $baseConfig with $config in $($config.Directory)..."
    XmlDocTransform "$($config.Directory)\$baseConfig" "$($config.Directory)\$config";

Credit for the bulk of this comes from this stackoverflow answer

Leave a Reply

Your email address will not be published. Required fields are marked *