Powershell – Strange behavior from Invoke-WebRequest in scheduled task

powershellscheduled-task

I'm running a PowerShell script that posts data to an internal webserver over HTTPS. The SSL certificate is not valid. I'm using

[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}

to accept the certificate and it works when the script is ran from the command line but I get the error

You must write ContentLength bytes to the request stream before calling [Begin]GetResponse.

when ran as a scheduled task. The exact command is

Invoke-WebRequest -Uri 'https://host/login.cgi' -Method POST -Body 'username&password' -UseBasicParsing

Best Answer

In the end, I just reverted to more basic .NET functionality:

[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
[System.Net.ServicePointManager]::Expect100Continue = $false

$cookies = New-Object System.Net.CookieContainer

$request = [System.Net.HttpWebRequest]::Create('https://host')
$request.Method = 'POST'
$request.CookieContainer = $cookies

$postData = 'stringdata'
$data = [System.Text.Encoding]::ASCII.GetBytes($postData)
$request.ContentLength = $data.Length

$requestStream = $request.GetRequestStream()
$requestStream.Write($data, 0, $data.Length)
$requestStream.Close()

$response = [System.Net.HttpWebResponse]$request.GetResponse()
$responseStream = $response.GetResponseStream()

(New-Object System.IO.StreamReader($responseStream)).ReadToEnd()
Related Topic