2013-08-29 24 views
27

Ho questo documento XML in un file di testo:Come eseguire l'iterazione tramite XML in 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> 

voglio scorrere ogni oggetto e trovare il DisplayName e ServiceState. Come potrei farlo? Ho provato tutti i tipi di combinazioni e sto lottando per risolverlo.

sto facendo questo per ottenere il codice XML in una variabile:

[xml]$priorServiceStates = Get-Content $serviceStatePath;

dove $serviceStatePath è il nome del file xml mostrato sopra. Allora ho pensato che avrei potuto fare qualcosa di simile:

foreach ($obj in $priorServiceStates.Objects.Object) 
{ 
    if($obj.ServiceState -eq "Running") 
    { 
     $obj.DisplayName; 
    } 
} 

E in questo esempio vorrei una stringa emesso con SQL Server (MSSQLSERVER)

risposta

31

PowerShell ha funzioni built-in XML e XPath. È possibile utilizzare il cmdlet Select-Xml con una query XPath per selezionare i nodi dall'oggetto XML e quindi .Node. "# Testo" per accedere al valore del nodo.

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

o meno lungo

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

ho aggiunto qualche spiegazione. – mswietlicki

+1

Puoi anche navigare nel documento usando la sintassi della proprietà familiare: '($ xml.Objects.Object |? {$ _. ServiceState -eq" Running "}). DisplayName' – zneak

Problemi correlati