2012-10-22 64 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。 –