In the previous tip we illustrated how Invoke-WebRequest can be used to download JSON or XML data from a web page. This example downloads the psconf.eu agenda in JSON format:

$page = Invoke-WebRequest -Uri powershell.beer -UseBasicParsing 
$($page.Content | ConvertFrom-Json) | Out-GridView

And this example downloads currency exchange rates in XML format:

$url = 'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml'
$result = Invoke-WebRequest -Uri $url -UseBasicParsing
$xml = [xml]$result.Content
$xml.Envelope.Cube.Cube.Cube 

Now, there is another cmdlet called Invoke-RestMethod which is specifically designed to work with object data. Basically, it works like Invoke-WebRequest but automatically recognizes the data format, and converts it accordingly. This is how you can get the psconf.eu agenda in just one line:

$(Invoke-RestMethod -Uri powershell.beer -UseBasicParsing) | Out-GridView

And this is how you can simplify processing the currency exchange rates:

$url = 'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml'
(Invoke-RestMethod -Uri $url -UseBasicParsing).Envelope.Cube.Cube.Cube

Twitter This Tip! ReTweet this Tip!

Anonymous