使用PowerShell替换嵌套XML中的值

问题描述 投票:0回答:1

如何使用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> ```
xml powershell xml-parsing powershell-3.0 powershell-4.0
1个回答
0
投票

您可以尝试这个

# 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"

foreach ($add in $xml.Tester.application.add)
{
  # value before
  $add.value
  # modification
  if ($add.value -eq "false")
  {
    $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")
© www.soinside.com 2019 - 2024. All rights reserved.