您好我正在尝试更改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)
我已经修改了下面的代码,但它仍然无法正常工作,我收到了同样的错误。
$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)
答案 0 :(得分:7)
迟到了,但万一有人可能会找到它的用途,我已经写了一个可重复使用的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)
答案 1 :(得分:3)
这是一个循序渐进的例子:
[xml]$x='<connectionStrings>
<add name="membership" connectionString="Data Source=server1;Initial Catalog=inventory;MultipleActiveResultSets=true;user id=inventoryWebUser;password=123456" providerName="System.Data.SqlClient" />
<add name="test" connectionString="Data Source=server1;Initial Catalog=inventory;MultipleActiveResultSets=true;user id=inventoryWebUser;password=123456" providerName="System.Data.SqlClient" />
</connectionStrings>'
$mycon=$x.connectionStrings.add |?{$_.name -eq "membership"}
$mycon.connectionString=$mycon.connectionstring -replace "password=123456","password=admin123"
$x.save("c:\temp\newconf.xml")
gc c:\temp\newconf.xml
答案 2 :(得分:1)
一种肮脏的方法可能是在不解析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