Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
}

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