0

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.

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

1 Comment

it did the trick. I am now able to add new values without changing the existing one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.