1
votes

I am trying to use Powershell to update a single XML child node property by index. In the below sample I want to update only the second Import Filename="File_2.txt" property

<!--test.xml -->
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <node1 test="hello"/>
  <node2>
    <Import Filename="File_1.txt" />
    <Import Filename="File_2.txt" />
    <Import Filename="File_3.txt" />
   </node2>
</configuration>

([xml] ( gc "test.xml" )).configuration.node1.test #displays hello
([xml] ( gc "test.xml" )).configuration.node2.Import.Filename[1] #displays File_2.txt

Ok so it looks like i have the right node references, So now i update the child nodes

$xml = ([xml] ( gc "test.xml" ))
$xml.configuration.node1.test = "something new"
$xml.Save( "test.xml" )
$xml.configuration.node1.test #Displays something new

$xml = ([xml] ( gc "test.xml" ))
$xml.configuration.node2.Import.Filename[1] = "ImaNewFile.txt"
$xml.Save( "test.xml" )
$xml.configuration.node2.Import.Filename[1] #Displays File_2.txt

The configuration.node1.test was updated to something new,
The configuration.node2.Import.Filename[1] is still displaying File_2.txt

Why wasn't the second configuration.node2.Import.Filename updated?

2

2 Answers

2
votes

Change

$xml.configuration.node2.Import.Filename[1] = "ImaNewFile.txt"

to

$xml.configuration.node2.Import[1].Filename = "ImaNewFile.txt"

I believe $xml.configuration.node2.Import.Filename is just a string array which has no connection to the xml nodes, however I believe $xml.configuration.node2.Import[1] is a reference to the actual xml node.

1
votes
$xml.configuration.node2.Import[1].Filename

instead of

$xml.configuration.node2.Import.Filename[1]

I did not test it, just from the logic of the provided snippet, it seems that you need to have the index at the element not the attribute.

I think you can take this as a general rule, since XML allows duplicate named child nodes but not attributes. So having the index at the attribute is never working.

Using the PowerShell ISE debugger might also help to find solutions in similar situations by going to the script "step by step".