Knowledge Base

Preserving for the future: Shell scripts, AoC, and more

Powershell: Invoke-WebRequest with custom cookie

In Powershell 7.3 on MacOS, you can run Invoke-WebRequest (iwr) with a -Headers that includes "Cookie" and it works. I'm guessing the Windows implementation of iwr does not let you do this, in Powershell 5.1 or 7.4.

$s = New-Object Microsoft.PowerShell.Commands.WebRequestSession
$c = New-Object System.Net.Cookie('AppCookie',$value,'/','example.com')
$s.Cookies.Add($c)

$Response = Invoke-WebRequest "https://example.com/path/to/endpoint" -WebSession $s

References

There's a few places out on the Internet that describe how to set cookies for a request.

  1. HTTP requests with PowerShell’s Invoke-WebRequest – by Example - David Hamann
  2. Powershell Invoke-WebRequest with a cookie | GripDev

Comments