Powershell update xml key value based on other key value


I'm trying to write some powershell that will update the value of a xml key value pair based on the value of another key value pair in the same node. Example xml:

<?xml version="1.0" encoding="utf-8" ?>
  <plugin pluginType="plugin1" polling_internal="2" polling_unit="M" enabled="true">
        <add key="Server" value="server1.local" />
        <add key="database" value="databasename1" />
  <plugin pluginType="plugin2" polling_internal="2" polling_unit="M" enabled="true">
        <add key="Server" value="server2.local" />
        <add key="database" value="databasename2" />

The real file has hundreds of plugins in it. I want to find all instances of databases called databasename1 - <add key="database" value="databasename1" and update the corresponding Server key with server name server2.local for example.

I know this can be done with select-xml and xpath, but its beyond me. Any assistance much appreciated.


Something like this should do the trick:

[Xml]$oXml = Get-Content oldfile.xml

$sXPath = "/configuration/plugins/plugin/params/add[@value='databasename1']"
$cChildren = $oXml.SelectNodes($sXPath)

foreach ($oChild in $cChildren) {
    $oParent = $oChild.get_ParentNode()
    $oServer = $oParent.ChildNodes | Where-Object { $_.key -eq "Server" }
    $oServer.value = "server2.local"

$oXml.OuterXml | Out-File newfile.xml

Should be doable with less code if you use a more complex XPath.

You can use this XPath to get all value attribute according to the criteria you explained (xpath formatted for readability) :

    /params[add[@key='database' and @value='databasename1']]

The most complicated part (line 2 in above xpath) means search

By : har07

This video can help you solving your question :)
By: admin