我在文本文件中有这个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>
我想迭代每个对象,找到DisplayName和ServiceState.我该怎么办?我尝试了各种组合,并努力解决这个问题.
我这样做是为了将XML转换为变量:
[xml] $priorServiceStates = Get-Content $serviceStatePath;
其中$serviceStatePath是上面显示的xml文件名.然后我想我可以这样做:
foreach ($obj in $priorServiceStates.Objects.Object) { if($obj.ServiceState -eq "Running") { $obj.DisplayName; } }
PowerShell具有内置的XML和XPath功能.
您可以将Select-Xml cmdlet与XPath查询一起使用,从而从XML对象中选择节点
.Node.’#text’来访问节点值.
原文链接:https://www.f2er.com/xml/293050.html您可以将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'}
或者更短
[xml]$xml = Get-Content $serviceStatePath Select-Xml "//Object[Property/@Name='ServiceState' and Property='Running']/Property[@Name='DisplayName']" $xml | % {$_.Node.'#text'}