Web.Config transforms outside of Microsoft MSBuild?

后端 未结 8 2096
情书的邮戳
情书的邮戳 2020-11-29 18:13

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

8条回答
  •  -上瘾入骨i
    2020-11-29 18:53

    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:

    • Find all config files recursively
    • Find all transform templates for the environment we are in #passed in as a parameter
    • For each transform file, find the corresponding config
    • Then do transform
    • Code runs a postdeploy script to remove all unwanted transform files.

提交回复
热议问题