2013-08-29 34 views
27

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 DisplayNameServiceState. 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)

Trả lời

31

PowerShell đã tích hợp chức năng XML và XPath. Bạn có thể sử dụng lệnh ghép ngắn Select-Xml với truy vấn XPath để chọn các nút từ đối tượng XML và sau đó .Node. '# Text' để truy cập giá trị nút.

[xml]$xml = Get-Content $serviceStatePath 
$nodes = Select-Xml "//Object[Property/@Name='ServiceState' and Property='Running']/Property[@Name='DisplayName']" $xml 
$nodes | ForEach-Object {$_.Node.'#text'} 

Hoặc ngắn

[xml]$xml = Get-Content $serviceStatePath 
Select-Xml "//Object[Property/@Name='ServiceState' and Property='Running']/Property[@Name='DisplayName']" $xml | 
    % {$_.Node.'#text'} 
+4

tôi đã thêm một số lời giải thích. – mswietlicki

+1

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

Các vấn đề liên quan