Invoke-RestMethod vs Invoke-WebRequest example

 Sometimes I look at old code and think 'Why did I do that? Why not xxxxxx'. Lately that was when looking at Invoke-WebRequest and Invoke-RestMethod.

I use both of these in the Service Health scripts when retrieving the access token for accessing the office 365 service health, messages etc.

So the quick answer is, Invoke-WebRequest returns the status (ie 200 OK, 404 not found) while Invoke-RestMethod returns the content that Invoke-WebRequest does, and converts it to json (depending on API)


So for example

Invoke-RestMethod -Uri https://icanhazdadjoke.com -Headers @{accept="application/json"} | Select-Object -ExpandProperty joke

returns a single line of the joke


Invoke-WebRequest -Uri https://icanhazdadjoke.com -Headers @{accept="application/json"} | Select-Object -ExpandProperty content | ConvertFrom-Json | Select-Object -ExpandProperty joke


The above command does the same, after expanding the content and converting.

Comments

Popular posts from this blog

Skype Online and MCOValidationError

SCCM 2012 R2 - Offline servicing error

Polycom provisioning - and Zoom!