Change web.config with powershell

I need to try updating the web.config file in order to change the IP address for web.config only. I have included the Im code section, which is considering powershell script change value.

<connectionStrings> <add name="connectionString" connectionString="provider=SQLOLEDB;Server=192.168.1.100;database=sample;Trusted_Connection=Yes" providerName="System.Data.OleDb" /> <add name="sqlConnectionString" connectionString="Data Source=192.168.1.100;Initial Catalog=sample;Trusted_Connection=Yes" providerName="System.Data.SqlClient" /> </connectionStrings> 

I would like a very simple solution to this, just update your ServerIP address.

Does anyone know an easy way to do this using PowerShell.

+4
source share
2 answers

I would say the following

 $cfg = [xml](gc web.config) # Replace all references of the IP in all connection string $cfg.configuration.connectionStrings.add|%{ $_.connectionString = $_.connectionString -replace "192.168.1.100", "1.0.0.1"; } $cfg.Save("Web.config"); 

If you just want to replace the specified connection string, I would select it like this:

 $con= $cfg.configuration.connectionStrings.add|?{$_.name -eq "SqlDataCon"}; # Replace the content $con.connectionString = $con.connectionString -replace "192.168.1.100", "1.0.0.1" 
+8
source

You can try:

 $xml = [xml](Get-Content c:\temp\web.config) $conString = $xml.connectionStrings.add[0].connectionString $conString2 = $conString -replace '192.168.1.100','10.10.10.10' $xml.connectionStrings.add[0].connectionString = $conString2 $conString = $xml.connectionStrings.add[1].connectionString $conString2 = $conString -replace '192.168.1.100','10.10.10.10' $xml.connectionStrings.add[1].connectionString = $conString2 $xml.Save('c:\temp\web2.config') 

This task is for two connection strings. If you do not want to hardcode the old IP address you can use:

 $conString -replace 'Server=.*;','Server=10.10.10.11;' 
+2
source

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


All Articles