如何在Powershell中阅读XML?

前端之家收集整理的这篇文章主要介绍了如何在Powershell中阅读XML?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在文本文件中有这个XML文档: @H_404_1@<?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>

我想遍历每个对象,并找到DisplayName和ServiceState。我该怎么做?我试过各种组合,并努力工作它。

我这样做将XML变成一个变量:

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

其中$ serviceStatePath是上面显示的xml文件名。然后我想我可以做一些像:

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

在这个例子中,我想要一个字符串输出sql Server(MSsqlSERVER)

PowerShell具有内置的XML和XPath函数
您可以使用Select-Xml cmdlet与XPath查询从XML对象中选择节点
.Node。’#text’来访问节点值。 @H_404_1@[xml]$xml = Get-Content $serviceStatePath $nodes = Select-Xml "//Object[Property/@Name='ServiceState' and Property='Running']/Property[@Name='DisplayName']" $xml $nodes | ForEach-Object {$_.Node.'#text'}

或更短

@H_404_1@[xml]$xml = Get-Content $serviceStatePath Select-Xml "//Object[Property/@Name='ServiceState' and Property='Running']/Property[@Name='DisplayName']" $xml | % {$_.Node.'#text'}
原文链接:https://www.f2er.com/xml/293518.html

猜你在找的XML相关文章