如何在Powershell中迭代XML ?

时间:2022-06-01 16:50:37

I have this XML document in a text file:

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

I want to iterate through each object and find the DisplayName and ServiceState. How would I do that? I've tried all kinds of combinations and am struggling to work it out.

我要遍历每个对象并找到DisplayName和ServiceState。我该怎么做呢?我尝试过各种各样的组合,我都在努力想办法解决它。

I'm doing this to get the XML into a variable:

我这样做是为了把XML变成一个变量:

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

(xml)priorServiceStates =获取内容serviceStatePath美元;

where $serviceStatePath is the xml file name shown above. I then thought I could do something like:

$serviceStatePath是上面显示的xml文件名。然后我想我可以这样做:

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

And in this example I would want a string outputted with SQL Server (MSSQLSERVER)

在本例中,我希望使用SQL Server (MSSQLSERVER)输出字符串

1 个解决方案

#1


32  

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.

PowerShell具有内置的XML和XPath函数。您可以使用select - XML cmdlet和XPath查询从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'}

Or shorter

或更短

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

#1


32  

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.

PowerShell具有内置的XML和XPath函数。您可以使用select - XML cmdlet和XPath查询从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'}

Or shorter

或更短

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