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

Viewed 248

I need to replace the tag value into one file from another file by using powershell script.

Example:

File A:

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

Below value need to be replaced every time I execute the script:

<BRANCH>MASTER</BRANCH>

File B: (Here Branch name will update every time and I need to replace the dynamic values from this file into the File A's Branch tag)

FileName: branch.txt

Value: Branch-Name

PS: It should not append the file A, just replace the values

I've tried below powershell script but it's appending the value instead of replacing and also it works only with static values.

Here .runsettings is my File A name

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

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

$replace value will change every time, there will be a different branch name everytime, so my powershell script should be able to read the values inside from File B (Contains the branch name ex: develop or any other) and able to just replace the value in File A (.runsettings BRANCH tag) as mentioned above.

I don't know how to fetch the dynamic value from File B and replace it on runtime with File A's BRANCH value.

1 Answers

In general it is a bad practice to peek and poke directly into a structured text files (like XML) using string methods as Replace. Instead it is recommended to use the related (XML) parser.
As an example:

$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\work\5eb597bdb0233b69\test.xml')
Related