2012-10-22 62 views
5

的app.config项节点的值具有以下的app.config:替换在PowerShell中

<configuration> 
<appSettings> 
<add key="filepath" value="D:\Data" /> 
<add key="node2" value="..." /> 
... 
</appSettings> 
</configuration> 

我想通过替换“d来替换具有新值“文件路径”键(设置:\数据..' 在这种情况下)。新值应该作为参数传递给powershell脚本。由于

回答

6

更新基于注释:

$xml = [xml]'<configuration> 
<appSettings> 
<add key="filepath" value="D:\Data" /> 
<add key="filename" value="test.log" /> 
</appSettings> 
</configuration>' 

$xml.configuration.appSettings.add | foreach { if ($_.key -eq 'filepath') { $_.value = "C:\Data" } } 
$xml.Save("C:\dell\NewApp.config") 

================================ ================================================== =========

OLD ANSWER

$xml = [xml]'<configuration> 
<appSettings> 
<add key="filepath" value="D:\Data" /> 
</appSettings> 
</configuration>' 

$xml.configuration.appSettings.add.value = "C:\Data" 
$xml.Save("NewApp.config") 

$xml = [xml](Get-Content App.config) 
$xml.configuration.appSettings.add.value = "C:\Data" 
$xml.Save("NewApp.Config") 
+0

我得到以下错误:无法在此对象上找到属性'值';确保它存在并可设置。似乎我需要以某种方式告诉它找到appSetting的'filepath'节点? –

+0

那么,你看到在配置中有多个节点。正确?如果是这样,请用包含更多添加节点的示例更新您的问题。 – ravikanth

+0

更新后的答案真的为我节省了很多时间,并可能重新整个项目。但是,在这一刻出现的一个错误(虽然现在不阻止我)在这一刻是“无法将值转换为类型”System.Xml.XmlDocument“” 如果你能帮助我,请欣赏@ravikanth。 –