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

时间:2021-09-18 08:03:28

How can I change the value of the node <Test>Test</Test> to <Test>Power</Test>?

如何将节点 Test 的值更改为 Power ?

Example:

例:

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

Here's the PowerShell script I currently use:

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

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

1 个解决方案

#1


21  

I don't know what exactly you want to achieve, but the example should give you and idea:

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

$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)

You don't need to use .NET for xpath queries. Just stay with PowerShell (with Select-Xml).
It is also common to load xml file via Get-Content and cast it to [xml] which creates XmlDocument and loads the file content.

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

#1


21  

I don't know what exactly you want to achieve, but the example should give you and idea:

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

$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)

You don't need to use .NET for xpath queries. Just stay with PowerShell (with Select-Xml).
It is also common to load xml file via Get-Content and cast it to [xml] which creates XmlDocument and loads the file content.

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