使用 powershell 在 config/xml 文件中找到密钥并替换其各自的值

Find the key and replace its respective value in config/xml files using powershell

我有一个类似于下面的配置文件:

<?xml version="1.0" encoding="utf-8"?>
<configuration>  
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
  </startup>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.1.1.3" newVersion="4.1.1.3" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-11.0.0.0" newVersion="11.0.0.0" />
      </dependentAssembly>      
    </assemblyBinding>
  </runtime>
  <appSettings>
    <add key="key1" value="Value1" />
    <add key="key2" value="Value12" />
    <add key="key3" value="Value3" />   
  </appSettings>
</configuration>

现在通过 powershell 我试图替换一些值,例如 Value1。为此,我编写了以下脚本:

$original_file = "C:\test.xml"
(Get-Content $original_file) | Foreach-Object {
     $_ -replace 'Value1', 'Newvalue'
    } | Set-Content $original_file

那么它的作用是用 Newvalue 字符串替换所有 Value1 字符串。我在这里面临的问题是它会在找到 Value1 的任何地方更改所有值,就像这样。

  <appSettings>
    <add key="key1" value="Newvalue" />
    <add key="key2" value="Newvalue2" /> --- this is not supposed to happen
    <add key="key3" value="Value3" />  
</appSettings>

而且在现实中,我的实际值是很长的字符串。

那么有什么方法可以找到密钥并更改其各自的值吗?就像找到 Key1 并将其值更改为 NewValue

非常感谢任何帮助。

Don't use regex against structured markup - 使用 XPath!

# Load the xml document
$filename = 'C:\test.xml'
$xmlDoc = New-Object xml
$xmlDoc.Load($filename)

# Select all applicable nodes
$nodes = $xmlDoc.SelectNodes('//appSettings/add[@key="key1"]')

# In each node, replace the value `Value1` with `NewValue`
foreach($node in $nodes){
  $node.value = $node.value.Replace('Value1','NewValue')
}

# Save the document
$xmlDoc.Save($filename)

XPath 表达式 //appSettings/add[@key="key1"] 将 select 任何 add 节点,该节点具有名为 key 的属性,值为 key1 并且其父节点是 appSettings节点.