Is it possible to use Microsoft\'s XML document transform, for preparing web.configs, outside of MSBuild? I would like to use PowerShell to do these transform without having
So extended slightly to work recursively
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";
}
$scriptPath = (Get-Variable MyInvocation -Scope 1).Value.InvocationName | split-path -parent
Add-Type -LiteralPath "$scriptPath\Microsoft.Web.XmlTransform.dll"
$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($xml);
}
function DoConfigTransform($webFolder, $environment)
{
$allConfigFiles = Get-ChildItem $webFolder -File -Filter *.config -Recurse
$transformFiles = $allConfigFiles | Where-Object {$_.Name -like ("*." + $environment + ".config")} | %{$_.fullname}
ForEach($item in $transformFiles)
{
$origFile = $item -replace("$environment.",'')
XmlDocTransform -xml $origFile -xdt $origFile$item
#Write-Output ("orig = " + $origFile + ", transform = " + $item)
}
cd C:\WebApplications\xxx\xxx\xxx\
.\PostDeploy.ps1
}
DoConfigTransform -webFolder "C:\WebApplications\xxx\xxx\xxx" -environment "xx-xxx-xx"
So the DoConfigTransform logic goes:
I updated the script a bit to make it work with the latest version of powershell and make it a bit easier.
function XmlDocTransform($xml, $xdt)
{
$scriptpath = $PSScriptRoot + "\"
$xmlpath = $scriptpath + $xml
$xdtpath = $scriptpath + $xdt
if (!($xmlpath) -or !(Test-Path -path ($xmlpath) -PathType Leaf)) {
throw "Base file not found. $xmlpath";
}
if (!($xdtpath) -or !(Test-Path -path ($xdtpath) -PathType Leaf)) {
throw "Transform file not found. $xdtpath";
}
Add-Type -LiteralPath "$PSScriptRoot\Microsoft.Web.XmlTransform.dll"
$xmldoc = New-Object Microsoft.Web.XmlTransform.XmlTransformableDocument;
$xmldoc.PreserveWhitespace = $true
$xmldoc.Load($xmlpath);
$transf = New-Object Microsoft.Web.XmlTransform.XmlTransformation($xdtpath);
if ($transf.Apply($xmldoc) -eq $false)
{
throw "Transformation failed."
}
$xmldoc.Save($xmlpath);
Write-Host "Transformation succeeded" -ForegroundColor Green
}
And to invoke the function use
XmlDocTransform "App.config" "App.acc.config"