使用 PowerShell 替换嵌套 XML 中的值

Replace Values in Nested XML Using PowerShell

如何使用 Powershell 替换嵌套 xml 中的值?

如何使用 PowerShell 将 "Racers"、"Pacers" "Losers" 的值从 "false" 替换为 "True"?

<Tester>
<TesterSection>
 <section name="TestingApp" type="Amazon,Google" />
</TesterSection>
<application>
 <add key="Minimum" value="1" />
 <add key="Maximum" value="true" />
 <add key="Runners" value="N/A" />
 <add key="Racers" value="false" />
 <add key="Pacers" value="false" />
 <add key="Losers" value="false" />
</application>  
</Tester> ```

你可以试试这个

# Simulate the XML in a string
$text = @"
<Tester>
<TesterSection>
 <section name="TestingApp" type="Amazon,Google" />
</TesterSection>
<application>
 <add key="Minimum" value="1" />
 <add key="Maximum" value="true" />
 <add key="Runners" value="N/A" />
 <add key="Racers" value="false" />
 <add key="Pacers" value="false" />
 <add key="Losers" value="false" />
</application>  
</Tester>
"@

$xml = [xml]$text
# You can load the file with
# $xml = [xml] "c:\temp\thefile.xml"

# List of keys to change
$tochange = "Racers","Pacers","Losers"

foreach ($add in $xml.Tester.application.add)
{
  # value before
  $add.value
  # modification
  if ($tochange -contains $add.key)
  {
    $add.value= "true"
  }
  # name after
  $add.value
}
# Or in a sigle line
#$xml.Tester.application.add | % {if ($_.value -eq "false"){$_.Value ="true"}}
$xml.Save("c:\temp\FileAfter.xml")

另一个建议是使用xpath。这是您示例的工作截图

[xml]$xml = @"
<Tester>
    <TesterSection>
        <section name="TestingApp" type="Amazon,Google" />
    </TesterSection>
    <application>
        <add key="Minimum" value="1" />
        <add key="Maximum" value="true" />
        <add key="Runners" value="N/A" />
        <add key="Racers" value="false" />
        <add key="Pacers" value="false" />
        <add key="Losers" value="false" />
    </application>  
</Tester>
"@

foreach ($key in $("Racers","Pacers","Losers")) {
    $xml.selectNodes("//application/add[@key='$key']") | %{ $_.value = "true" }
}
$xml.Save("c:\temp\FileAfter.xml")