I have been searching through multiple explanations, but I don't seem to be able to find a solution.
My XML looks like this:
<?xml version="1.0" encoding="utf-8"?>
<ConfigRightCollection>
<ConfigRight Name="CreateSampling">
<GroupCollection>
<Group>All</Group>
</GroupCollection>
</ConfigRight>
<ConfigRight Name="InputMeasure">
<GroupCollection>
<Group>All</Group>
</GroupCollection>
</ConfigRight>
<ConfigRight Name="AllowCreateOnStoppedJob">
<GroupCollection>
<Group>Admin</Group>
</GroupCollection>
</ConfigRight>
</ConfigRightCollection>
I want to add to new elements to the 'ConfigRight Name = "AllowCreateOnStoppedJob' group so that it looks like this:
<?xml version="1.0" encoding="utf-8"?>
<ConfigRightCollection>
<ConfigRight Name="CreateSampling">
<GroupCollection>
<Group>All</Group>
</GroupCollection>
</ConfigRight>
<ConfigRight Name="InputMeasure">
<GroupCollection>
<Group>All</Group>
</GroupCollection>
</ConfigRight>
<ConfigRight Name="AllowCreateOnStoppedJob">
<GroupCollection>
<Group>Admin</Group>
<Group>QS</Group>
<Group>QU</Group>
</GroupCollection>
</ConfigRight>
</ConfigRightCollection>
My code so far that seems to work:
$filePath = "\\some\path\to\the\file.xml"
[xml]$xmlData = Get-Content -Path $filePath
$xmlData | Select-Xml -XPath '/ConfigRightCollection/ConfigRight' | Where-Object{ ($_.Node.Name -eq "AllowCreateOnStoppedJob") } | Select-Object -ExpandProperty "Node"
But the code to actually add the new elements does not work, I receive the error "cannot call a method on a null-valued expression":
$newGroups = "QS","QU"
ForEach ($group in $newGroups)
{
# Creation of a sub node
$xmlSubElt = $xmlData.GroupCollection.CreateElement("Group")
$xmlSubText = $xmlData.GroupCollection.CreateTextNode($group)
$xmlSubElt.AppendChild($xmlSubText)
}
$xmlData.Save
The part that I cannot seem to resolve is how do I select the correct ConfigRight element and add 2 new elements to its GroupCollection sub-element? I am limited to PS 5.1