Skip to content

Instantly share code, notes, and snippets.

@lawrencegripper
Last active January 18, 2024 06:34
Show Gist options
  • Save lawrencegripper/6bee7de123bea1936359 to your computer and use it in GitHub Desktop.
Save lawrencegripper/6bee7de123bea1936359 to your computer and use it in GitHub Desktop.
Invoke-webrequest With Cookie
$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
@sgezel
Copy link

sgezel commented Feb 4, 2020

Here is a snippet using the code above to read cookies from a netscape formatted cookies.txt file and insert them into the webrequest

if(Test-Path .\cookies.txt -PathType Leaf)
{

  
    $downloadToPath = "c:\somewhere\on\disk\file.zip"
    $remoteFileLocation = "http://somewhere/on/the/internet"
  

    $session = New-Object Microsoft.PowerShell.Commands.WebRequestSession

    foreach($line in Get-Content .\cookies.txt) {
        if(!$line.StartsWith("#")){
        
            $split = $line.Split("`t")
                    
            $cookie = New-Object System.Net.Cookie 
    
            $cookie.Name = $split[5]
            $cookie.Value = $split[6]
            $cookie.Domain = $split[0]

            $session.Cookies.Add($cookie);

        }
    }

    Invoke-WebRequest $remoteFileLocation -WebSession $session -TimeoutSec 900 -OutFile $downloadToPath
}

@KnightChaser
Copy link

What an excellent example, appreciate it!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment