powershell: invoke-webrequest does not always write cookie into session variable RRS feed

  • Question

  • Hi all, 

    I want to get a webpage's cookie into the sessionvariable using invoke-webrequest. There seems to be a timing issue on when the cookie is set by the page that determines on whether I receive it in the variable. This is how my script looks like:

    $sitesToTry = "","","","",""
    foreach ($url in $sitesToTry) {
        $webrequest = Invoke-WebRequest -Uri $url -SessionVariable websession -UseBasicParsing -MaximumRedirection 3
        Write-Output "************** cookies *******************"
        Write-Output $url
        Write-Output $websession.Cookies
        $cookies = $websession.Cookies.GetCookies($url) 
        # Here, you can output all of $cookies, or you can go through them one by one. 
        foreach ($cookie in $cookies) { 
            # You can get cookie specifics, or just use $cookie 
            # This gets each cookie's name and value 
            Write-Host "$($ = $($cookie.value)" 
    (I took it from ). If I run that script several times, I might see a different number of cookies (e.g. sometimes I see a cookie for, sometimes I don't). For some pages like facebook, I never see a cookie, although they set one (I checked with IE dev console). Any ideas on what causes that behavior and how to get around it? I got the impression, that I have a general problem with javascript pages, but that is a guess for now.

    • Moved by Bill_Stewart Thursday, December 13, 2018 3:20 PM This is not "develop custom solutions for me" forum
    Wednesday, September 19, 2018 10:49 AM