The underlying connection was closed: An unexpected error occurred on a receive. when using Invoke-RestMethod from Azure powershell runbook

Question:

I’m trying to send Microsoft Azure Alerts to Google Chat room (Hangouts) from within Azure Powershell Runbook. From time to time the message is sent without any issues, but roughly in half of the tries it returns the error below:

Line 43 of my script looks like this

Where $uriHangouts is the webhook address and the $body is message according to the schema provided here:
https://developers.google.com/hangouts/chat/reference/message-formats/basic

As it is testing only, I’m sending every time exactly the same message. It is a basic one with some markup.
If I forward it to Azure Logic App and resend it from there to Hangouts, it works every time.
If I send it from my PC, it works every time as well.
So far, I’ve tried without any success to use Invoke-WebRequest instead Invoke-RestMethod, and force TLS 1.2 (1.1) with the following line:

I’m literally out of ideas where to go next.

Please, help!
Thank you in advance!

Answer:

You do not need to use Invoke-WebRequest instead Invoke-RestMethod, you just need to run ​[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 before executing Invoke-RestMethod as this blog mentioned.

And if you want use Invoke-WebRequest instead Invoke-RestMethod, you can have a try with add -UseBasicParsing after Invoke-WebRequest command.

Source:

The underlying connection was closed: An unexpected error occurred on a receive. when using Invoke-RestMethod from Azure powershell runbook by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply