xml - 如何在 Powershell 中遍历 XML?

标签 xml powershell

我在一个文本文件中有这个 XML 文档:

<?xml version="1.0"?>
<Objects>
  <Object Type="System.Management.Automation.PSCustomObject">
    <Property Name="DisplayName" Type="System.String">SQL Server (MSSQLSERVER)</Property>
    <Property Name="ServiceState" Type="Microsoft.SqlServer.Management.Smo.Wmi.ServiceState">Running</Property>
  </Object>
  <Object Type="System.Management.Automation.PSCustomObject">
    <Property Name="DisplayName" Type="System.String">SQL Server Agent (MSSQLSERVER)</Property>
    <Property Name="ServiceState" Type="Microsoft.SqlServer.Management.Smo.Wmi.ServiceState">Stopped</Property>
  </Object>
</Objects>

我想遍历每个对象并找到 DisplayNameServiceState。我该怎么做?我已经尝试了各种组合并且正在努力解决它。

我这样做是为了将 XML 放入变量中:

[xml]$priorServiceStates = Get-Content $serviceStatePath;

其中 $serviceStatePath 是上面显示的 xml 文件名。然后我想我可以做类似的事情:

foreach ($obj in $priorServiceStates.Objects.Object)
{
    if($obj.ServiceState -eq "Running")
    {
        $obj.DisplayName;
    }
}

在这个例子中,我想要一个用 SQL Server (MSSQLSERVER)

输出的字符串

最佳答案

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

[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'}

关于xml - 如何在 Powershell 中遍历 XML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18509358/

相关文章:

powershell - 如何让我的脚本允许任何参数?

java - 从 Java 调用 Powershell 脚本

Powershell设置新本地用户强制更改密码

c# - Selectnodes 只获取第一个节点

xml - 如何安全地处理 Scala 中的 unicode 用户输入(尤其是 XML 实体)

java - 我在 intellij IDEA 中看不到 Jaxb 工具

powershell - Get-Unique 和 select-object -unique 的区别

sql - FOR XML SQL 查询生成记录头

xml - 加载远程 xml 文件

powershell - 更改脚本以不同方式导出组和嵌套对象