2010-07-08 38 views
9

如何將節點的值 <Test>Test</Test>更改爲 <Test>Power</Test>如何使用PowerShell更新XML節點的值?

<?xml version="1.0"?> 
<configuration> 
    <appSettings> 
     <add key="DeploymentDate" value="test" /> 
     <add key="DateOfInitialization" value="Vinoj" /> 
    </appSettings> 
    <Test>Test</Test> 
</configuration> 

這裏的PowerShell腳本我目前使用的:

$configuration = "app.config" 
[xml]$xml = New-Object XML 
$xml.Load($configuration) 
$xml.selectnodes("/configuration/Test") = {"UST"} 
$xml.Save($configuration) 

回答

21

我不知道你要實現什麼,但例子應該給你的想法:

$file = 'c:\temp\aa\ServerService.exe.config' 
$x = [xml] (Get-Content $file) 
Select-Xml -xml $x -XPath //root/level | 
    % { $_.Node.'#text' = 'test' 
     $_.Node.SomeAttribute = 'value' 
     } 
$x.Save($file) 

您不需要使用.NET for xpath queri ES。留在PowerShell中(與Select-Xml)。
通過Get-Content加載xml文件並將其轉換爲[xml],這會創建XmlDocument並加載文件內容。

+0

工作就像一個魅力。你能告訴我什麼| %一般嗎? – 2013-10-31 07:14:48

+3

這意味着'foreach-object'。你可以用'Get-Alias -Name%' – stej 2013-11-01 10:04:51

+0

找到它,你也可以訪問'$ xml.configuration.test'測試值 - 非常漂亮(因爲它不是集合),但是你可以使用'foreach $ xml.things){$ thing.value}'。我在這裏,因爲我需要在增加版本後保存我的XML文件。這幫助了我。 +1 – ppumkin 2015-10-15 12:14:39