2009-11-30 27 views
7

Quando mi collego al mio HP ILO utilizzando l'URL, http://ilo-ip/xmldata?item=All restituisce un file XML nel formato seguente.Come leggere il file XML dal web utilizzando PowerShell

<?xml version="1.0" ?> 
- <RIMP> 
- <HSI> 
    <SPN>ProLiant DL385 G1</SPN> 
    <SBSN>ABCDEFG</SBSN> 
    <UUID>123456789</UUID> 
    </HSI> 
- <MP> 
    <ST>1</ST> 
    <PN>Integrated Lights-Out (iLO)</PN> 
    <FWRI>1.82</FWRI> 
    <HWRI>ASIC: 2</HWRI> 
    <SN>ILOABCDEFG</SN> 
    <UUID>ILO1234545</UUID> 
    </MP> 
    </RIMP> 

C'è qualche PowerShell comando/script per leggere i dati XML da URL web?

risposta

14

PowerShell utilizza XmlDocument NET Framework così si potrebbe chiamare il metodo load per caricare il codice XML in un oggetto XmlDocument come questo:

#Option 1  
$doc = New-Object System.Xml.XmlDocument 
$doc.Load("http://ilo-ip/xmldata?item=All") 

#Option 2 
[xml]$doc = (New-Object System.Net.WebClient).DownloadString("http://ilo-ip/xmldata?item=All") 


# Your XML will then be in the $doc and the names of the XML nodes can be used as 
# properties to access the values they hold. This short example shows how you would 
# access the value held in the SPN nodes from your sample XML 
Write-Host $doc.RIMP.HSI.SPN 

Se la vostra ricerca di maggiori informazioni su come lavorare con l'XML, una volta che ha stato caricato controllare Dr. Tobias Weltner's eBook su PowerShell.com, chapter 14 copre XML.

+0

Grazie per la risposta. Come leggo il codice che viene caricato? Non ho potuto trovare molto aiuto in internet. –

+1

l'XML verrà conservato nell'oggetto $ doc in modo che sia possibile accedervi tramite la notazione delle proprietà. Ad esempio Write-Host $ doc.RIMP.HSI.SPN Questo scriverà "ProLiant DL385 G1" sulla console. Quello che puoi fare è inviare $ doc a Get-Member per ottenere un elenco di proprietà, ad es. $ doc | Get-Member –

+0

Ciao Alan, ho ricevuto un'eccezione Quando ho caricato l'xml in entrambi i modi come hai descritto. L'eccezione è "Il server ha commesso una violazione del protocollo Section = ResponseStatusLine" ' –

8

Sicuro. È possibile utilizzare l'oggetto .NET WebClient per scaricare XML dal Web e quindi utilizzare il tipo [xml] per interpretare una stringa come XML in questo modo:

$url = "http://blogs.msdn.com/powershell/rss.xml" 
[xml]$xml = (new-object System.Net.WebClient).DownloadString($url) 
$xml.rss.channel | Foreach {$_.item} | 
    Where {[DateTime]$_.pubDate -gt (Get-Date).AddMonths(-1)} | 
    Format-Table Title 
Problemi correlati