Modify web.config with powershell

 

Questions


I need to try to update a web.config file to change the IP address only of the web.config
I have included the section of code Im looking at for powershell to script the change.

<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 the ServerIP address.

Anyone know an easy way to do this with PowerShell.

 

 

————————————————-

Answer

I’d to 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 are just looking to replace a specfic connection string, I’d fetch 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"

connection-string,powershell,powershell-v3.0,web-config

Leave a Reply

Your email address will not be published. Required fields are marked *