如何使用PowerShell从Web读取XML文件

Sit*_*thi 8 xml powershell

当我使用URL连接到HP ILO时,http:// ilo-ip/xmldata?item =全部 它以下面的格式返回XML文件.

  <?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>
Run Code Online (Sandbox Code Playgroud)

是否有任何powershell命令/脚本从Web URL读取XML数据?

小智 17

PowerShell使用.Net框架XmlDocument,因此您可以调用load方法将xml加载到XmlDocument对象中,如下所示:

#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
Run Code Online (Sandbox Code Playgroud)

如果您在加载XML后查找有关使用XML的更多信息,请参阅PowerShell.com上的Tobias Weltner博士的电子书,第14章介绍了XML.


Kei*_*ill 8

当然.您可以使用.NET WebClient对象从Web下载XML,然后使用[xml]类型将字符串解释为XML,如下所示:

$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
Run Code Online (Sandbox Code Playgroud)