如何在 Powershell 中遍历 XML? [英] How to iterate through XML in Powershell?

查看:57
本文介绍了如何在 Powershell 中遍历 XML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have this XML document in a text file:

<?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.我该怎么做?我尝试了各种组合,但都在努力解决.

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.

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

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

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

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

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

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

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

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

推荐答案

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

这篇关于如何在 Powershell 中遍历 XML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆