Search code examples
xmlpowershellxml-parsingpowershell-3.0powershell-4.0

Replace Values in Nested XML Using PowerShell


How to replace the values in nested xml using Powershell?

How do i replace the values of "Racers", "Pacers" "Losers" from "false" to "True" using PowerShell ?

<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> ```

Solution

  • You can try this

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