I am trying to open a webpage with Invoke-WebRequest and when I use the
-Session
parameter, it is empty, am I using it correctly? I've noticed the page does not display to Invoke-WebRequest unless I already have cookies saved from visiting the page manually through Chrome and I copy the development tools generated code into Powershell for testing. I have tried to duplicate the answer from this post ( Using Invoke-Webrequest in powershell with cookies ) for the past few days and cannot result in generating any cookies.
Is there a way to query the page initially and generate cookies for the session, so that they may be used throughout the rest of the requests?
$url = "http://xxxxx/Reports/report/xxxxx%20Reports/Testing/Status%20Report";
$reqTest = Invoke-WebRequest -UseDefaultCredentials -UseBasicParsing -Uri $url -SessionVariable sessionTest;
$sessionTest.Cookies
Capacity Count MaxCookieSize PerDomainCapacity
300 0 4096 20
When I access the page via Chrome and then go into dev tools and right click --> copy --> copy all as Powershell and run that code in Powershell, I am able to read the page for the time the cookies are good for and when I view the cookies, they contain data as shown below
$session = New-Object Microsoft.PowerShell.Commands.WebRequestSession
$session.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36"
$session.Cookies.Add((New-Object System.Net.Cookie("XSRF-TOKEN", "deprecated", "/", "xxxxx")))
$session.Cookies.Add((New-Object System.Net.Cookie("displayedContent", "%7B%22hidden%22%3Afalse%7D", "/", "xxxxx")))
$session.Cookies.Add((New-Object System.Net.Cookie("XSRF-NONCE", "Pwg30pQR%2B409Aik0MA5R8fYet2Ve%3D", "/", "xxxxx")))
$session.Cookies.Add((New-Object System.Net.Cookie("ai_user", "rrV1V|2023-08-02T12:31:42.622Z", "/", "xxxxx")))
$session.Cookies.Add((New-Object System.Net.Cookie("ai_authUser", "0B02E81106FD8C30BC5DF6FDEF66%7C27a1c-dd5e-4e3f-b5a4-5f6249a", "/", "xxxxx")))
$request = Invoke-WebRequest -UseBasicParsing -Uri "http://xxxxx/Reports/report/xxxxx%20Reports/Testing/Status%20Report" `
-WebSession $session `
-UseDefaultCredentials `
-Headers @{
"Accept"="text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7"
"Accept-Encoding"="gzip, deflate"
"Accept-Language"="en-US,en;q=0.9"
"Cache-Control"="max-age=0"
"If-Modified-Since"="Wed, 26 Jun 2019 16:07:36 GMT"
"If-None-Match"="`"1d52c66542`""
"Upgrade-Insecure-Requests"="1"
};
$session.Cookies
Capacity Count MaxCookieSize PerDomainCapacity
300 8 4096 20