我在文本文件中有这个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’来访问节点值。
您可以使用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'}