Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify web.config with powershell

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.

like image 420
Sc-python-leaner Avatar asked May 30 '13 03:05

Sc-python-leaner


People also ask

How do I change the value of web config file in PowerShell?

For a web. config file, start with $cfg = (Get-Content "C:\inetpub\wwwroot\mysite\web. config") -as [Xml] , then $x would be $cfg. configuration, i.e. $cfg.

Does PowerShell have a config file?

A powershell. config. json file in the $PSHOME directory defines the configuration for all PowerShell sessions running from that PowerShell installation. The $PSHOME location is defined as the same directory as the executing System.

How do I comment multiple lines in web config?

ctl K + C combination to comment that line... to uncomment ctl K + U combination is used.


2 Answers

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"
like image 86
Harald F. Avatar answered Sep 21 '22 16:09

Harald F.


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 do the job for the two connection strings. If you don't want to hard code the old IP address you can use :

$conString -replace 'Server=.*;','Server=10.10.10.11;'
like image 25
JPBlanc Avatar answered Sep 21 '22 16:09

JPBlanc