Doing XDT transformations like MSBuild or SlowCheetah with Powershell

Transformations of XML-configuration files in the same way as Visual Studio might be helpful in Powershell, for instance as part of a Continuous Deployment scenario – Octopus Deploy is our weapon of choice for that. There are various solutions around, but I wanted to make mine simple, so I basically refactored a very lightweight C# solution by Eric Hexter based off the Microsoft.Web.XmlTransform.dll. That solution lives here at Github.

My essential Powershell XDT transformer looks like this:

# Transform with XDT
$scriptPath = (Split-Path -Parent $MyInvocation.MyCommand.Definition) + "\" # Script Directory

$src = $scriptPath + "input.config"
$xdt = $scriptPath + "transform.config"
$dst = $scriptPath + "output.config"

Add-Type -Path "c:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v11.0\Web\Microsoft.Web.XmlTransform.dll"

try 
{
    $doc = New-Object Microsoft.Web.XmlTransform.XmlTransformableDocument
    $doc.PreserveWhiteSpace = $true
    $doc.Load($src)

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

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

I am still asking myself whether this kind of code ought to be in a custom C# based CmdLet module, callable by Powershell, at least as long as Powershell lives such a strange life outside Visual Studio – but the jury is still out on that…

Advertisements

One thought on “Doing XDT transformations like MSBuild or SlowCheetah with Powershell

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s