A
A
ArtemiyFedorov2021-10-25 19:28:53
PowerShell
ArtemiyFedorov, 2021-10-25 19:28:53

How to edit XML in PowerShell?

Greetings!
Faced a problem to edit xml in powershell. It's not tricky, but something is going wrong.
Below is a simplified piece of xml, I need to change the SerialConnectionTimeout parameter.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <applicationSettings>
    <Vendor.Some.App.Properties.Settings>
      <setting name="TimeoutStep" serializeAs="String">
        <value>300</value>
      </setting>
      <setting name="TimeoutDuration" serializeAs="String">
        <value>5000</value>
      </setting>
      <setting name="SerialConnectionTimeout" serializeAs="String">
        <value>1000</value>
      </setting>
    </Vendor.Some.App.Properties.Settings>
  </applicationSettings>
</configuration>


I'm trying to read it like this:
$xml = New-Object -TypeName XML
$file = 'C:\config.xml'
$xml.Load($file)
$xml.configuration.applicationSettings.'Vendor.Some.App.Properties.Settings'.setting.SerialConnectionTimeout

- I get NULL. There are not quite the objects that I expected to see. The properties are not named, I can't refer to them by name - objects have standard properties name, value.
You can read it using the where construct, but I don’t see the point, since I need to edit this data and save it back with the same structure.
$xml.configuration.applicationSettings.'Vendor.Some.App.Properties.Settings'.setting.name `
| where {$_.name -eq "SerialConnectionTimeout"} | select -ExpandProperty value


I understand that I first need to somehow deserialize / convert the array of Settings into familiar objects, change it, serialize it back and save it, but I also couldn’t deserialize it right away.
How to edit correctly?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Bezrukov, 2021-10-25
@ArtemiyFedorov

did you try that?

$node = $xml.configuration.applicationSettings.'Vendor.Some.App.Properties.Settings'.setting `
| where {$_.name -eq "SerialConnectionTimeout"}
$node.Value = "yourvalue"
...
$xml.Save($file)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question