Author Posts

May 16, 2017 at 8:29 pm

Hi,

I have a question about Invoke-WebRequest cmdlet. I'm trying to use it to login into a website, and download a report (Excel file).
To login I'm using POST method, and I don't have a problem with this part, but in the next step when I'm trying to download the file, instead of getting my data, the excel file contains login page...
Any idea where I'm making a mistake?


[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

$reportxlsx = "C:\My Files\report.xlsx"

$r = Invoke-WebRequest -Uri https://www.mywebsite.com/ -SessionVariable st
$form = $r.Forms[0]
$form.Fields["USER"]="username"
$form.Fields["USERID"]="userid"
$form.fields["PASSWORD"]="mypassword"
$form.fields["GROUP"]="mygroup"
$form.Fields["smagentname"]="randomstring"
$form.Fields["smauthreason"]="0"
$form.Fields["stopAutoFill"]=""
$form.Fields["target"]="https://www.mywebsite.com/folderwithreport"
$form.Fields

$r = Invoke-WebRequest -Uri ("https://www.mywebsite/forms/login.fcc" + $form.Action) -WebSession $st -Method Post -Body $form.Fields -OutFile $Text
$r = Invoke-WebRequest -Uri ("https://www.mywebsite.com/repository/iB4CCFF7457124F1389C589D9470521D9") -WebSession $st -Method Get -OutFile $reportxlsx

May 17, 2017 at 2:23 am

Yup. You aren't saving the login cookie and then passing it back on subsequent requests. See the example in the help file for that command for a Facebook example.

May 17, 2017 at 1:33 pm

Hi Don,

I thought that's what the

 -SessionVariable st 

is doing? I actually did follow all the steps from the help file (Facebook example) and I'm still getting this error:

Invoke-WebRequest : The server committed a protocol violation. Section=ResponseHeader Detail=CR must be followed by LF

May 17, 2017 at 1:37 pm

Ah, you didn't share that error earlier. The server response appears to be formed in a way that the command doesn't like.
I'd honestly have to troubleshoot this using a low level tool like Postman, so I could see all the raw headers and whatnot. I'd need to ensure the cookie was going into the request header correctly and see what the server is actually producing. It's not gonna be simple :(.