Home > Mobile >  Update XML value with PowerShell
Update XML value with PowerShell

Time:04-26

I have some XML that is driving me crazy. I'm trying to simply update the XML file located in $env:USERNAME\Appdata\Local\file.xml. I cannot for the life of me work out how to find the value for SoftPhoneHotDeskExtension & SoftPhoneHotDeskCode and update them.

<NavigatePro>
  <UserPref>
    <Attribute Name="NavigateProInstalling">
      <Value>0</Value>
      <Type Value="4">DWord</Type>
    </Attribute>
    <Attribute Name="PlantronicsHeadsetSupportEnable">
      <Value>0</Value>
      <Type Value="1">String</Type>
    </Attribute>
    <Attribute Name="SoftPhoneHotDeskExtension">
      <Value>999</Value>
      <Type Value="1">String</Type>
    </Attribute>
    <Attribute Name="SoftPhoneHotDeskCode">
      <Value>888</Value>
      <Type Value="1">String</Type>
    </Attribute>
  </UserPref>
</NavigatePro>

I can list them out by name by using:

[xml]$XMLfile = Get-Content c:\users\$env:USERNAME\Appdata\Local\file.xml
$XMLFile.NavigatePro.UserPref.Attribute

This will show me the list of attributes by name and value but I cannot fathom how to update them and save them back. I have looked at XPath and using SingleNode but to no avail. Most of the errors come back stating they cannot find the node I'm looking for.

CodePudding user response:

If I understand you correctly, xpath is the solution here:

$extension = $xml.SelectSingleNode("//Attribute[@Name='SoftPhoneHotDeskExtension']/Value")
$extension.innerText="xxx"
$hdcode = $xml.SelectSingleNode("//Attribute[@Name='SoftPhoneHotDeskCode']/Value")
$hdcode.innerText="yyy"

and that should do it.

CodePudding user response:

Another way would be to use the case-insensitive 'dot-notation':

$file = "$env:USERNAME\Appdata\Local\file.xml"
$xml  = [System.Xml.XmlDocument]::new()
$xml.Load($file)

($xml.navigatepro.userpref.attribute | Where-Object {$_.Name -eq 'softphonehotdeskextension'}).Value = '1234'
($xml.navigatepro.userpref.attribute | Where-Object {$_.Name -eq 'softphonehotdeskcode'}).Value = '5678'
$xml.Save($file)

To make sure your xml gets the encoding of the file correct, I suggest you use the .Load() method of the XmlDocument Class instead of casting the result of Get-Content to [xml]

  • Related