Coding, How to, powershell

Powershell Invoke-WebRequest with a cookie

Nice and quick post here, mainly so I remember when I need it again, this is a quick sample which shows how to make a web call from PowerShell including a cookie.

Most old methods will suggest using the WebClient object but the new (well newer than the WebClient) Invoke-WebRequest commandlet is a much nicer, in my opinion.

It takes a bit of fooling around to get this up and running so wanted to share.

$downloadToPath = "c:\somewhere\on\disk\file.zip"
$remoteFileLocation = "http://somewhere/on/the/internet"
$session = New-Object Microsoft.PowerShell.Commands.WebRequestSession
$cookie = New-Object System.Net.Cookie
$cookie.Name = "cookieName"
$cookie.Value = "valueOfCookie"
$cookie.Domain = "domain.for.cookie.com"
$session.Cookies.Add($cookie);
Invoke-WebRequest $remoteFileLocation -WebSession $session -TimeoutSec 900 -OutFile $downloadToPath
Standard

2 thoughts on “Powershell Invoke-WebRequest with a cookie

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s