将标签值从一个文件替换为另一个文件的 PowerShell 脚本(标签值)

PowerShell script to replace the tag value from one file to another file (tag value)

我需要使用 powershell 脚本将标签值从另一个文件替换到一个文件中。

示例:

文件A:

<?xml version="1.0" encoding="utf-8"?>
<RunSettings>
    <RunConfiguration>
        <EnvironmentVariables>          
      <BRANCH>MASTER</BRANCH>
    </EnvironmentVariables>
    </RunConfiguration>
</RunSettings>

每次执行脚本都需要替换以下值:

<BRANCH>MASTER</BRANCH>

文件 B:(这里的分支名称每次都会更新,我需要将这个文件中的动态值替换到文件 A 的分支标签中)

文件名: branch.txt

:分支名称

PS:不应该附加文件A,只是替换值

我试过下面的 powershell 脚本,但它是附加值而不是替换值,而且它只适用于静态值。

这里.runsettings是我的A文件名

$filePath = 'C:\BuildAgent\workeb597bdb0233b69\.runsettings'
$tempFilePath = "C:\BuildAgent\workeb597bdb0233b69\.runsettings"
$find = '<BRANCH>main</BRANCH>'
$replace = '<BRANCH>develop</BRANCH>'

(Get-Content -Path $filePath) -replace $find, $replace | Add-Content -Path $tempFilePath

$replace 值每次都会改变,每次都会有不同的分支名称,所以我的 powershell 脚本应该能够从文件 B 中读取里面的值(包含分支名称 ex: develop 或任何其他)和如上所述,只需替换文件 A(.runsettings BRANCH 标记)中的值即可。

我不知道如何从文件 B 获取动态值并在运行时用文件 A 的 BRANCH 值替换它。

一般来说,使用字符串方法 Replace 直接查看和戳入结构化文本文件(如 XML)是一种不好的做法。相反,建议使用相关的 (XML) 解析器。
例如:

$Xml = [Xml]'<?xml version="1.0" encoding="utf-8"?>
<RunSettings>
  <RunConfiguration>
    <EnvironmentVariables>
      <BRANCH>Master</BRANCH>
    </EnvironmentVariables>
  </RunConfiguration>
</RunSettings>'

$Xml.RunSettings.RunConfiguration.EnvironmentVariables.BRANCH = 'Develop'

$Xml.Save('C:\BuildAgent\workeb597bdb0233b69\test.xml')