Tôi có tài liệu XML này trong một tập tin văn bản:Làm thế nào để lặp qua XML trong Powershell?
<?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>
Tôi muốn lặp qua từng đối tượng và tìm ra DisplayName
và ServiceState
. Tôi sẽ làm như thế nào? Tôi đã thử tất cả các loại kết hợp và đang đấu tranh để giải quyết nó.
tôi đang làm điều này để có được XML vào một biến:
[xml]$priorServiceStates = Get-Content $serviceStatePath;
nơi $serviceStatePath
là tên tập tin xml hiển thị ở trên. Sau đó tôi nghĩ tôi có thể làm một cái gì đó như:
foreach ($obj in $priorServiceStates.Objects.Object)
{
if($obj.ServiceState -eq "Running")
{
$obj.DisplayName;
}
}
Và trong ví dụ này, tôi sẽ muốn có một chuỗi outputted với SQL Server (MSSQLSERVER)
tôi đã thêm một số lời giải thích. – mswietlicki
Bạn cũng có thể điều hướng tài liệu bằng cú pháp thuộc tính quen thuộc: '($ xml.Objects.Object |? {$ _. ServiceState -eq" Đang chạy "}). DisplayName' – zneak