N997
N997

Reputation: 157

Appending attribute value in a XML document via Powershell

I have been trying to develop a script in powershell that could update / append new attribute values ( do not change existing values ) separated by " , " up to 4 values.

The format of the file is

    <configuration>
      <appSettings>        
         <add key="servername" value="server1"/>
      </appSettings>          
   </configuration>

Desired result is

   <configuration>
      <appSettings>        
         <add key="servername" value="server1,server2,server3,server3,server4"/>
      </appSettings>          
   </configuration>

I can add new value but cannot retain the old one by below code

$file = "C:\Users\test\Desktop\server.exe.config"
$xml = [xml] (Get-Content $file)
$XPpath = "/configuration/appSettings/add[@key='servername']"
$nodes = $xml.SelectNodes($XPpath)

foreach ( $n in $nodes ) {
        $n.value = $n.value = 'server2'
        }

I read help documents / searched online but could not find any tip on how to achieve the desired result. Anything I am missing? Your help is appreciated.

Upvotes: 0

Views: 334

Answers (1)

Daniel
Daniel

Reputation: 5112

You're close. Value is a string so just append what you want to it like you would any other string. I use += below to do this.

$xml = [xml]@'
<configuration>
<appSettings>
   <add key="servername" value="server1"/>
</appSettings>
</configuration>
'@

$XPpath = "/configuration/appSettings/add[@key='servername']"
$nodes = $xml.SelectNodes($XPpath)

foreach ( $n in $nodes ) {
    $n.value += ',server2,server3,server4,server5'
}

# or
# $xml.configuration.appSettings.add.value += ",server2,server3,server4"


$xml.configuration.appSettings.add.value
# output: server1,server2,server3,server4,server5

$xml.Save(".\new.xml")

# new.xml:
# <configuration>
#   <appSettings>
#     <add key="servername" value="server1,server2,server3,server4,server5" />
#   </appSettings>
# </configuration>

Upvotes: 1

Related Questions