我尝试使用PowerShell
更改web.config文件中的应用设置以下是web.config文件;
<configuration>
<connectionStrings>
<add name="TestDBEntities" connectionString="metadata=res://*/TestProject.csdl|res://*/TestProject.ssdl|res://*/TestProject.msl;provider=System.Data.SqlClient;provider connection string="data source=SQL01;initial catalog=TestDB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<appSettings>
<add key="ActivePeriod" value="false" />
<add key="Environment" value="UAT" />
<add key="authmode" value="4" />
<add key="IsEncryptedConfig" value="true" />
<add key="LogErrorsToText" value="true" />
</appSettings>
</configuration>
我想更改应用设置值。为此,我已将所有相应的值存储在PowerShell字典中。 这是我的字典看起来像;
Key Value
----- -----
ActivePeriod true
Environment prod
LogErrorsToText false
现在,我希望将每个词典键与appsetting键匹配。如果任何字典键与appsetting键匹配,则应替换相应的值。就我而言,我期待以下输出;
<configuration>
<connectionStrings>
<add name="TestDBEntities" connectionString="metadata=res://*/TestProject.csdl|res://*/TestProject.ssdl|res://*/TestProject.msl;provider=System.Data.SqlClient;provider connection string="data source=SQL01;initial catalog=TestDB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<appSettings>
<add key="ActivePeriod" value="true" />
<add key="Environment" value="prod" />
<add key="authmode" value="4" />
<add key="IsEncryptedConfig" value="true" />
<add key="LogErrorsToText" value="false" />
</appSettings>
</configuration>
有人可以建议我可能的解决方案。提前谢谢。
答案 0 :(得分:3)
迭代字典中的Keys
,在Xml文档中找到相应的<add />
节点,然后设置属性,如果找到:
$xml = [xml](Get-Content .\app.config)
$Dictionary = @{
ActivePeriod = 'true'
Environment = 'prod'
LogErrorsToText = 'false'
}
foreach($key in $Dictionary.Keys)
{
Write-Host "Locating key: '$key' in XML"
# Use XPath to find the appropriate node
if(($addKey = $xml.SelectSingleNode("//appSettings/add[@key = '$key']")))
{
Write-Host "Found key: '$key' in XML, updating value to $($Dictionary[$key])"
$addKey.SetAttribute('value',$Dictionary[$key])
}
}
答案 1 :(得分:0)
Mathias R. Jenssen 的答案很好地概述了如何做事,但正如 OP 在他/她的答案的评论中所提到的,它不是开箱即用的(对于更高版本的 PowerShell至少,我在 PS 5.1 上测试过)。
什么对我有用:
$xml = [xml](Get-Content '.\app.config')
$Dictionary = @{
ActivePeriod = 'true';
Environment = 'prod';
LogErrorsToText = 'false';
}
foreach($key in $Dictionary.Keys)
{
Write-Host "Locating key: '$key' in XML"
# Use XPath to find the appropriate node
if(($addKey = $xml.SelectSingleNode("//appSettings/add[@key = '$key']")))
{
Write-Host "Found key: '$key' in XML, updating value to $($Dictionary[$key])"
$addKey.SetAttribute('value',$Dictionary[$key])
}
}
$xml.Save('.\app.config')
注意区别在于哈希表声明的半列。我根据 official Microsoft documentation 进行了此更改。
此外,根据 OP 在评论中的要求,最后一行显示了如何保存 xml 文件。