Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

powershell - Editing an XML object - Connection Strings

I have an XML config loaded into my script as an xml object called $appConfig. I am trying to replace the connection string value with a string of my own. This is what I have so far which finds the target string:

$appConfig.configuration.connectionStrings.add |
    ? {$_.name -eq $dbName} |
    select connectionString

I essentially want something akin to this:

$appConfig.configuration.connectionStrings.add |
    ? {$_.name -eq $dbName} |
    select connectionString = $updatedConnectionString

I'm pretty sure I need to make a variable and populate it with the $appConfig but everytime I try I just end up with another XML object instead of editing the target $appConfig object as intended. I write the $appConfig back to its original file location and complete the edit. I just can't seem to get the right syntax here.

My XML example related to the strings:

<configuration>
<connectionStrings>
    <add name="db" connectionString="Data Source=(local);Initial Catalog=MyDB;Integrated Security=True" providerName="System.Data.SqlClient" />
    <add name="dbFiles" connectionString="Data Source=(local);Initial Catalog=MyDB;Integrated Security=True" providerName="System.Data.SqlClient" />
    <add name="dbReporting" connectionString="Data Source=(local);Initial Catalog=MyDB;Integrated Security=True" providerName="System.Data.SqlClient" />
    <add name="Logging" connectionString="Data Source=(local);Initial Catalog=MyDB;Integrated Security=True" providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you want to use dot-notation, you could do something like this:

$node = $appConfig.configuration.connectionStrings.add |
        Where-Object {$_.name -eq $dbName}
$node.connectionString = $updatedConnectionString
$appConfig.Save()

or like this (if you don't want to assign the selected node to a variable before modifying its attribute):

($appConfig.configuration.connectionStrings.add | Where-Object {$_.name -eq $dbName}).connectionString = $updatedConnectionString
$appConfig.Save()

Another way would be to use the SelectSingleNode() method with an XPath expression, e.g. like this:

($appConfig.SelectSingleNode("//add[@name='$dbName']").connectionString = $updatedConnectionString
$appConfig.Save()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...