且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Powershell 中遍历 XML?

更新时间:2023-11-24 21:05:46

PowerShell 具有内置的 XML 和 XPath 函数.您可以使用 Select-Xml cmdlet 和 XPath 查询从 XML 对象中选择节点,然后.Node.'#text' 访问节点值.

PowerShell has built-in XML and XPath functions. You can use the Select-Xml cmdlet with an XPath query to select nodes from XML object and then .Node.'#text' to access node value.

[xml]$xml = Get-Content $serviceStatePath
$nodes = Select-Xml "//Object[Property/@Name='ServiceState' and Property='Running']/Property[@Name='DisplayName']" $xml
$nodes | ForEach-Object {$_.Node.'#text'}

或更短

[xml]$xml = Get-Content $serviceStatePath
Select-Xml "//Object[Property/@Name='ServiceState' and Property='Running']/Property[@Name='DisplayName']" $xml |
  % {$_.Node.'#text'}