2013-05-30 110 views
4

我需要嘗試更新web.config文件以更改web.config的IP地址 我已經包含了代碼部分,我正在尋找powershell來編寫腳本。使用powershell修改web.config

<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> 

我想一個很簡單的解決這個 只需更新服務器IP地址。

任何人都知道一個簡單的方法來使用PowerShell做到這一點。

回答

8

我倒是下面

$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"); 

如果你只是希望更換specfic連接字符串,我'd取它像這樣:

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

謝謝,工作得很好 –

2

你可以試試:

$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') 

這兩個連接字符串做的工作。如果你不想硬編碼舊的IP地址,你可以使用:

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