ATTENTION: You are viewing a page formatted for mobile devices; to view the full web page, click HERE.

Other Software > Developer's Corner

Searching and updating XML file in PowerShell


I have the following bit in a Powershell script:

--- Code: PowerShell ---[xml]$xmlConfig = Get-Content "odata.xml"$validNodes = $xmlConfig | Select-Xml -XPath '//variable' | %{$_ | ?{((($_.Node.Property.Name -eq "id") -and ($_.Node.Property.Value -eq "this-is-the-node")))}}if ($validNodes.Count -gt 0) {     $validNodes.development = $encryptedcredentials}
And it's not returning valid nodes, even though the node is there.

The XML file looks like the following:

--- Code: Text ---<configuration>  <variable>    <id>this-is-not-the-node</id>    <development>2</development>    <staging>0</staging>    <production>0</production>  </variable>  <variable>    <id>this-is-the-node</id>    <development>2</development>    <staging>0</staging>    <production>0</production>  </variable>  <variable>    <id>this-is-not-the-node-either</id>    <development>2</development>    <staging>0</staging>    <production>0</production>  </variable></configuration>
I want to select the valid node, then edit the value for development under that node.

Any ideas what I'm doing wrong?

Wouldn't it be easier to use a simple xpath expression to extract the matching element(s)?

--- ---Select-Xml -XPath "//variable[id='this-is-the-node']"

The problem with that is that I don't want that node, I want the parent variable node so I can update the development value. I was under the impression that wouldn't help me, but I'll try it.

So I tried it, and it did indeed give me the subsection I was looking for- how would I then get the development subnode to change it?

And thanks for the help... this has been stumping me for a few days.

UPDATE: I think I found out how to modify the node, but even though when I expand it shows the node as modified, when I save, it never gets to the file.

--- Code: PowerShell ---[xml]$xmlConfig = Get-Content "odata.xml"$validNodes = $xmlConfig | Select-Xml -XPath &#39;//variable[id="odata-keys"]&#39; if ($validNodes.Count -gt 0) {   $validNodes.Node.development = "0"   $xmlConfig.Save("odata.xml")}
What am I doing wrong now?

In case anyone else is wondering, the problem was the assumption on the path.

I added

--- Code: PowerShell ---$outPath = (Resolve-Path odata.xml).Path# saves odata.xml in your current working directory$xmlConfig.Save($outPath)
and it started working.

Thanks for your help!


[0] Message Index

Go to full version