Editing a web configuration file using Microsoft PowerShell

I want to change my web config file using powershell. I'm stuck somewhere. I want to update appsettings as well as connectionstring settings at the same time when I change them in powershel

I have this code, but it only changes the value of apppsettings when I change it here and run it, but I also want to include the connection string here. How can i achieve this?

$webConfig = "C:\Inetpub\Wwwroot\application\web.config" $doc = new-object System.Xml.XmlDocument $doc.Load($webConfig) $doc.get_DocumentElement()."appsetting".add[0].value = "true" $doc.Save($webConfig) 

Here is my web config file

  <appSettings> <add key="mykey1" value="false"/> <add key="mykey2" value="true"/> <add key="mykey3" value="false"/> </appSettings> <connectionstrings> <add name="myname1" connectinstring="Data Source=ABDULLAH-PC\SQLEXPRESS;Initial Catalog=UserDataBase; Integrated Security=True" providerName="System.Data.SqlClient" /> <add name="myname2" connectinstring="myconnectionstring2" /> <add name="myname3" connectinstring="myconnectionstring3" /> </connectionStrings> 

Here I want upadate appsettings - (key and value), as well as connectionstrings (name and initial directory) at the same time

when i tried my code it gave me this error

 Property '#text' cannot be found on this object; make sure it exists and is settable. At line:3 char:66 + $doc.SelectSingleNode('//appSettings/add[@key="mykey1"]/@value'). <<<< '#text' = 'false' + CategoryInfo : InvalidOperation: (#text:String) [], RuntimeException + FullyQualifiedErrorId : PropertyNotFound Property '#text' cannot be found on this object; make sure it exists and is settable. At line:4 char:85 + $doc.SelectSingleNode('//connectionStrings/add[@name="myname1"]/@connectionstring'). <<<< '#text'='my_string' + CategoryInfo : InvalidOperation: (#text:String) [], RuntimeException + FullyQualifiedErrorId : PropertyNotFound 
+6
source share
1 answer
 $webConfig = "C:\Inetpub\Wwwroot\application\web.config" $doc = (gc $webConfig) -as [xml] $doc.SelectSingleNode('//appSettings/add[@key="mykey1"]/@value').'#text' = 'true' $doc.SelectSingleNode('//connectionStrings/add[@name="myname1"]/@connectionstring').'#text' = 'my_string' $doc.Save($webConfig) 

You can use XPath to select your nodes and set their value using the #text property that PowerShell adds.

Note. Your xml example has casing issues and some typos. Here is what I tested with:

 <root> <appSettings> <add key="mykey1" value="false"/> </appSettings> <connectionStrings> <add name="myname1" connectionstring="Data Source=ABDULLAH-PC\SQLEXPRESS;Initial Catalog=UserDataBase; Integrated Security=True" providerName="System.Data.SqlClient" /> </connectionStrings> </root> 
+18
source

Source: https://habr.com/ru/post/950409/


All Articles