42

我在一个文本文件中有这个 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>

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

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

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

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

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

在这个例子中,我想要一个输出的字符串SQL Server (MSSQLSERVER)

4

2 回答 2

51

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'}
于 2013-08-29T11:28:20.923 回答
2

您也可以在没有 [xml] 演员表的情况下执行此操作。(虽然 xpath 本身就是一个世界 。https://www.w3schools.com/xml/xml_xpath.asp

$xml = (select-xml -xpath / -path stack.xml).node
$xml.objects.object.property

或者只是这样,xpath 区分大小写。两者都有相同的输出:

$xml = (select-xml -xpath /Objects/Object/Property -path stack.xml).node
$xml


Name         Type                                                #text
----         ----                                                -----
DisplayName  System.String                                       SQL Server (MSSQLSERVER)
ServiceState Microsoft.SqlServer.Management.Smo.Wmi.ServiceState Running
DisplayName  System.String                                       SQL Server Agent (MSSQLSERVER)
ServiceState Microsoft.SqlServer.Management.Smo.Wmi.ServiceState Stopped
于 2019-01-22T17:55:58.890 回答