Skip to content

Instantly share code, notes, and snippets.

@Warrenn
Last active August 23, 2021 14:51
Show Gist options
  • Save Warrenn/a47426f248185c40a2c3 to your computer and use it in GitHub Desktop.
Save Warrenn/a47426f248185c40a2c3 to your computer and use it in GitHub Desktop.
Powershell script to transform a config file using a XML-Document-Transform file
function XmlDocTransform($xml, $xdt, $output)
{
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";
}
$transformDll = ""
if(Test-Path "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v12.0\Web\Microsoft.Web.XmlTransform.dll"){
$transformDll = "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v12.0\Web\Microsoft.Web.XmlTransform.dll"
}
if(($transformDll -eq "")-and(Test-Path "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v11.0\Web\Microsoft.Web.XmlTransform.dll")){
$transformDll = "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v11.0\Web\Microsoft.Web.XmlTransform.dll"
}
if(($transformDll -eq "")-and(Test-Path "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.XmlTransform.dll")){
$transformDll = "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.XmlTransform.dll"
}
if($transformDll -eq ""){
$scriptPath = (Get-Variable MyInvocation -Scope 1).Value.InvocationName | split-path -parent
$transformDll = "$($scriptPath)\Microsoft.Web.XmlTransform.dll"
}
Add-Type -Path $transformDll
$xmldoc = New-Object Microsoft.Web.XmlTransform.XmlTransformableDocument;
$xmldoc.PreserveWhitespace = $true
$xmldoc.Load($xml);
$transf = New-Object Microsoft.Web.XmlTransform.XmlTransformation($xdt);
if ($transf.Apply($xmldoc) -eq $false)
{
throw "Transformation failed."
}
$xmldoc.Save($output);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment