Using Invoke-Webrequest in powershell with cookies

I'd like to know how I can use Invoke-WebRequest and enable registeration of cookies. Currently there's a site that uses get/set and cookies and it's sort of built of thousands of pages. Each page consists the ID of the next page and I tried doing a loop that runs through and refers me to the last page, but because the webrequest doesnt keep the cookies, it keeps thinking im still on page 1.

How can I enable the storage of cookies for the webrequest so it wont think im still there?


You can use the session-related switches of Invoke-WebRequest. Your first request should use the -SessionVariable switch to choose the variable in which the cookies will be stashed:

iwr http://example.com/Page1 -SessionVariable session

Note the lack of $ on session - that command creates a variable with the given name. After that command, you have a $session variable, which you can then pass as the -WebSession in all subsequent requests:

iwr http://example.com/Page2 -WebSession $session

Example 2 in the Microsoft documentation on Invoke-WebRequest shows how to sign in to Facebook using this technique.