我在一个文本文件中有这个 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;
}
}
在这个例子中,我想要一个用 SQL Server (MSSQLSERVER)
最佳答案
PowerShell 具有内置的 XML 和 XPath 函数。 您可以使用带有 XPath 查询的 Select-Xml cmdlet 从 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'}
关于xml - 如何在 Powershell 中遍历 XML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18509358/