如何使用powershell更改web.config文件的值

san*_*san 8 powershell

您好我正在尝试更改web.config文件的连接字符串的值,但收到错误:

该物业'connectionString'不能在此对象上找到.验证该属性是否存在且可以设置.

这是我正在使用的脚本:

$webConfig = 'C:\Users\test\Desktop\web\web.config'
$doc = (Get-Content $webConfig) -as [Xml]
$obj = $doc.configuration.appSettings.add | where {$_.Key -eq 'CommandTimeOut'}
$obj.value = '60'
$config = [xml](gc $webConfig)  
$con= $config.configuration.connectionStrings.add|where-object{$_.name -eq "password"};

$con.connectionString = $con.connectionString -replace "123456", "admin1234"

$doc.Save($webConfig)
Run Code Online (Sandbox Code Playgroud)

我已经修改了下面的代码,但它仍然没有工作,我得到了同样的错误.

$cfg = [xml](gc $webConfig) 
$con= $cfg.configuration.connectionStrings.add|where-object{$_.name -eq "password"};
$cfg.configuration.connectionStrings.add.connectionString=   
$cfg.configuration.connectionStrings.add.connectionString -replace "123456","admin123"
$doc.Save($webConfig)
Run Code Online (Sandbox Code Playgroud)

Ill*_*ati 9

迟到了,但是为了防止有人找到它的用途,我已经写了一个可重复使用的Power-Shell.

    #set the value of this to your own db config
$myConnectionString = "Data Source=.;Initial Catalog=<Database>;Integrated Security=True";

$webConfig = '.\Api\Web.config'
$dbUpConfig = '.\Database\App.config'
$unitTestConfig = '.\Test\App.config'

Function updateConfig($config) 
{ 
$doc = (Get-Content $config) -as [Xml]
$root = $doc.get_DocumentElement();
$activeConnection = $root.connectionStrings.SelectNodes("add");
$activeConnection.SetAttribute("connectionString", $myConnectionString);
$doc.Save($config)
} 

updateConfig($webConfig)
updateConfig($dbUpConfig)
updateConfig($unitTestConfig)
Run Code Online (Sandbox Code Playgroud)


Loï*_*HEL 2

一种肮脏的方法可能是在不解析 xml 的情况下替换文本,如下所示(如果没有定义先前的连接字符串):

$replacementstring=@"
<connectionStrings>
  <add 
    name="NorthwindConnectionString" 
    connectionString="Data Source=serverName;Initial 
    Catalog=Northwind;Persist Security Info=True;User 
    ID=userName;Password=password"
    providerName="System.Data.SqlClient"
  />
</connectionStrings>
"@

(gc c:\temp\web.config) -replace "<connectionStrings/>" ,$repl  | out-file c:\temp\new_web.config
Run Code Online (Sandbox Code Playgroud)