Invoke-WebRequest & Invoke-RestMethod are, in my opinion, one of the greater functions of PowerShell. It is simple, but can provide a great amount of finesse when working on automation projects.
Getting started isn’t hard at all, and you’re most likely on a supported operating system like Windows 10 or Windows Server 2012 R2 and above.
Starting off simple, we can run Invoke-WebRequest to test an endpoint, as well as obtain some raw content/headers, etc. It will always attempt to parse HTML, not so much the data. With the -UseBasicParsing switch, it’ll do some RegEx HTML parsing, without this switch it reverts to the Internet Explorer COM API to parse the target.
Invoke-WebRequest -Uri 'https://jsonplaceholder.typicode.com/posts/1'
You can see that we’ve now been returned a number of parameters which can be used to debug, or test connectivity.
OK, so let’s try the same endpoint – but this time using Invoke-RestMethod.
That looks much better, doesn’t it? The difference is that Invoke-RestMethod has the capability to support JSON and XML content. It will attempt to detect the right decoder and does NOT support HTML (except if it is XML compliant).
The differences are apparent, and there will be use cases for both. For example, Invoke-WebRequest can be used for automating website tests and outputting the results, whereas Invoke-RestMethod can be used to facilitate the exchange of data more simply whether that is exporting to a CSV, writing directly to a SQL table or creating middle-ware to facilitate connectivity between multiple systems.