Using Session Variables in Web Requests

by | June 20,2019

Table of Contents

Why Some Web Requests Fail in PowerShell but Work in a Browser

Sometimes, web requests that work fine in a browser do not seem to work well in PowerShell. For example, when you navigate to http://www.geocode.xyz/Bahnhofstrasse,Hannover?json=1 in a browser, you get back the coordinates of that address in JSON format.

When you try the same within PowerShell, you get back awkward exceptions:

$url = 'http://www.geocode.xyz/Bahnhofstrasse,Hannover?json=1'
Invoke-RestMethod -Uri $url

The result is:

 
Invoke-RestMethod : { "success": false, "error": { "code": "006", "message": "Request Throttled." } }

The Key to Fixing Web Requests in PowerShell

The secret here is to get the session state first which includes the cookies and other details, then repeat the actual web service request with the session state.
Here is how it works:

$url = 'http://www.geocode.xyz'
$urlLocation = "$url/Bahnhofstrasse,Hannover?json=1"

$null = Invoke-RestMethod -Uri $url -SessionVariable session
Invoke-RestMethod -Uri $urlLocation -WebSession $session

Now the result looks right:

 
standard  : @{stnumber=1; addresst=Bahnhofstrasse; postal=30159; region=DE; prov=DE; city=Hannover; 
            countryname=Germany; confidence=0.8}
longt     : 9.73885
alt       : 
elevation : 
latt      : 52.37418  

Twitter This Tip! ReTweet this Tip!