use*_*896 6 powershell powershell-2.0 c#-4.0 powershell-3.0
我想使用PowerShell修改我的Web配置文件.我卡在某个地方.我想在powershel中更改它们的同时更新appsettings和connectionsstring信息
我有这个代码,但它改变了apppsettings值,当我在这里更改并运行它但我也想在这里包含connectionstring.我怎样才能实现它?
$webConfig = "C:\Inetpub\Wwwroot\application\web.config"
$doc = new-object System.Xml.XmlDocument
$doc.Load($webConfig)
$doc.get_DocumentElement()."appsetting".add[0].value = "true"
$doc.Save($webConfig)
Run Code Online (Sandbox Code Playgroud)
这是我的网络配置文件
<appSettings>
<add key="mykey1" value="false"/>
<add key="mykey2" value="true"/>
<add key="mykey3" value="false"/>
</appSettings>
<connectionstrings>
<add name="myname1" connectinstring="Data Source=ABDULLAH-PC\SQLEXPRESS;Initial Catalog=UserDataBase;
Integrated Security=True" providerName="System.Data.SqlClient" />
<add name="myname2" connectinstring="myconnectionstring2" />
<add name="myname3" connectinstring="myconnectionstring3" />
</connectionStrings>
Run Code Online (Sandbox Code Playgroud)
在这里,我想同时更新appsettings - (键和值)以及连接字符串(name和initialcatalog)
当我尝试你的代码时,它给了我这个错误
Property '#text' cannot be found on this object; make sure it exists and is settable.
At line:3 char:66
+ $doc.SelectSingleNode('//appSettings/add[@key="mykey1"]/@value'). <<<< '#text' = 'false'
+ CategoryInfo : InvalidOperation: (#text:String) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
Property '#text' cannot be found on this object; make sure it exists and is settable.
At line:4 char:85
+ $doc.SelectSingleNode('//connectionStrings/add[@name="myname1"]/@connectionstring'). <<<< '#text'='my_string'
+ CategoryInfo : InvalidOperation: (#text:String) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
Run Code Online (Sandbox Code Playgroud)
And*_*ndi 18
$webConfig = "C:\Inetpub\Wwwroot\application\web.config"
$doc = (gc $webConfig) -as [xml]
$doc.SelectSingleNode('//appSettings/add[@key="mykey1"]/@value').'#text' = 'true'
$doc.SelectSingleNode('//connectionStrings/add[@name="myname1"]/@connectionstring').'#text' = 'my_string'
$doc.Save($webConfig)
Run Code Online (Sandbox Code Playgroud)
您可以使用XPath选择节点并通过#textPowerShell添加的属性设置它们的值.
注意 - 你的示例xml有套管和一些拼写错误的问题.这是我测试的内容:
<root>
<appSettings>
<add key="mykey1" value="false"/>
</appSettings>
<connectionStrings>
<add name="myname1" connectionstring="Data Source=ABDULLAH-PC\SQLEXPRESS;Initial Catalog=UserDataBase; Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
</root>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10352 次 |
| 最近记录: |