Change All Keys in a XML Node in PowerShell

I have 2 XML Files. Both are pretty much the same, but with different key values. Both look like the example below, but with different values:

<SMSServerConf>
  <IP>localhost</IP>
  <Port>10010</Port>
  <Provider>3</Provider>
  <Link>192.168.0.146:2775</Link>
  <UserName>smppclient1</UserName>
  <Password>password</Password>
  <Apiid>smppclient1</Apiid>
  <Encoding>0</Encoding>
  <Ton>1</Ton>
  <Npi>1</Npi>
  <ValidityPeriod>20</ValidityPeriod>
  <ValidityPeriodEnable>true</ValidityPeriodEnable>
  <SenderName></SenderName>
</SMSServerConf>

Currently I use the code below to insert the values from one file to another:

$s_xml = [xml](Get-Content $s_location)
$d_xml = [xml](Get-Content $d_location)
$data = $s_xml.Configuration.SMSServerConf
$d_xml.Configuration.SMSServerConf.IP = $s_xml.Configuration.SMSServerConf.IP
$d_xml.Configuration.SMSServerConf.Port = $s_xml.Configuration.SMSServerConf.Port
$d_xml.Configuration.SMSServerConf.Provider = $s_xml.Configuration.SMSServerConf.Provider
$d_xml.Configuration.SMSServerConf.Link = $s_xml.Configuration.SMSServerConf.Link
$d_xml.Configuration.SMSServerConf.UserName = $s_xml.Configuration.SMSServerConf.UserName
$d_xml.Configuration.SMSServerConf.Password = $s_xml.Configuration.SMSServerConf.Password
$d_xml.Configuration.SMSServerConf.Apiid = $s_xml.Configuration.SMSServerConf.Apiid
$d_xml.Configuration.SMSServerConf.Encoding = $s_xml.Configuration.SMSServerConf.Encoding
$d_xml.Configuration.SMSServerConf.Ton = $s_xml.Configuration.SMSServerConf.Ton
$d_xml.Configuration.SMSServerConf.Npi = $s_xml.Configuration.SMSServerConf.Npi
$d_xml.Configuration.SMSServerConf.ValidityPeriod = $s_xml.Configuration.SMSServerConf.ValidityPeriod
$d_xml.Configuration.SMSServerConf.ValidityPeriodEnable = $s_xml.Configuration.SMSServerConf.ValidityPeriodEnable
$d_xml.Configuration.SMSServerConf.SenderName = $s_xml.Configuration.SMSServerConf.SenderName
$d_xml.Save($d_location)

At this point it looks like I will have to maintain the script every time key is added or removed. Is it possible to just indicate the node name and then iterate through each key and change the value instead of explicitly state every key separately?

1 answer

  • answered 2018-01-14 08:54 Ansgar Wiechers

    If you want to replace the entire content of a node it'd be simpler to just replace the entire node:

    [xml]$d_xml = Get-Content $d_location
    [xml]$s_xml = Get-Content $s_location
    
    $n1 = $d_xml.SelectSingleNode('/Configuration/SMSServerConf')
    $n2 = $s_xml.SelectSingleNode('/Configuration/SMSServerConf')
    $parent = $n1.ParentNode
    
    # remove existing node
    $parent.RemoveChild($n1) | Out-Null
    
    # add node from source XML
    $parent.AppendChild($d_xml.ImportNode($n2, $true)) | Out-Null