Home > Net >  How to use variables in XML tags in Powershell?
How to use variables in XML tags in Powershell?

Time:09-25

I am writing a powershell script that sets values in an XML object. The values I want to set are the X_# values in the following XML example

<config>
  <tag_1>
    <add key="yui" value="Y" />
  </tag_1>
  <tag_2>
    <add key="qwe" value="X_1" />
    <add key="abc" value=Y" />
  </tag_2>
  <tag_3>
    <add key="cdf" value="X_2" />
    <add key="abc" value="Y" />
  </tag_3>
  <tag_4>
    <add key="abc" value="X_3" />
  </tag_4>
</config>

For the key values I can use a list of keys and loop through it

$Fillvalue="New Value"
$key=qwe
$node=$XmlData.config.tag_3.add | where-object {$_.key -match $key}
$node.value=$Fillvalue

I have a hashtable of different key values, but how do I look through the tag_2 through tag_4

I tried using a variable instead of a tag name but that does not work.

$tag=tag_3
$node=$XmlData.config.$tag.add | where-object {$_.key -match $key} 

CodePudding user response:

A simple way to reference all the <tag> nodes under one <config> is .ChildNodes:

$key='abc'
$Fillvalue="New Value"
$xml.config.ChildNodes.Add |
  Where key -match $key | 
  Foreach {$_.value = $Fillvalue}

$xml.main.config.ChildNodes.Add  ## Outputs:

key value    
--- -----    
yui Y        
qwe X_1      
abc New Value
cdf X_2      
abc New Value
abc New Value

A more flexible way is with xmlpath:

Foreach ($node in $xml.SelectNodes("//*[contains(name(),'tag_')]")) {
    $node.add|? key -match $key|%{$_.value = $Fillvalue}
}

CodePudding user response:

I found that variables can be used as longs they are the end value and not in the middel, so

 $tag=tag_3
 $node=$XmlData.config.$tag.add | where-object {$_.key -match $key}

Does not work but

 $tag=tag_3
 $parent=$XmlData.config.$tag
 $node=$parent.add | where-object {$_.key -match $key}

works as expected.

  • Related