如何使用PowerShell更新XML节点的值?

SRA*_*SRA 10 powershell

如何将节点的值更改 <Test>Test</Test><Test>Power</Test>

示例:

<?xml version="1.0"?>
<configuration>
    <appSettings>
        <add key="DeploymentDate" value="test" />
        <add key="DateOfInitialization" value="Vinoj" />
    </appSettings>
    <Test>Test</Test>
</configuration>
Run Code Online (Sandbox Code Playgroud)

这是我目前使用的PowerShell脚本:

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

ste*_*tej 25

我不知道你想要实现什么,但这个例子应该给你和想法:

$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)
Run Code Online (Sandbox Code Playgroud)

您不需要使用.NET进行xpath查询.继续使用PowerShell(带Select-Xml).
通过加载xml文件Get-Content并将其强制转换[xml]为创建XmlDocument和加载文件内容也很常见.

  • 它意味着`foreach-object`.您可以使用`Get-Alias -Name%`找到它 (3认同)
  • 您还可以访问测试值 `$xml.configuration.test` - 非常漂亮(鉴于它不是一个集合),但是您可以使用 `foreach ($thing in $xml.things) { $thing.value } ` 。我在这里是因为我需要在增加版本后保存我的 XML 文件。这对我有帮助。+1 (3认同)