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

时间:2009-11-30 11:49:32

标签: xml powershell

当我使用URL http://ilo-ip/xmldata?item=All连接到HP ILO时,它将返回以下格式的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>

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

2 个答案:

答案 0 :(得分: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

如果您在加载XML后查找有关使用XML的更多信息,请在PowerShell.com上查看Dr. Tobias Weltner's eBookchapter 14涵盖XML。

答案 1 :(得分: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