title: The underlying connection was closed: An unexpected error occurred on a receive. when using Invoke-RestMethod from Azure powershell runbook
body: <p>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:</p>
  <pre><code>Invoke-RestMethod : The underlying connection was closed: An unexpected error occurred on a receive. 
  At line:43 char:1 
  + Invoke-RestMethod -uri $uriHangouts -Method Post -body $body -Content ... 
  + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
  + CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException 
  + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
  </code></pre>
  <p>Line 43 of my script looks like this</p>
  <pre><code>Invoke-RestMethod -uri $uriHangouts -Method Post -body $body -ContentType 'application/json'
  </code></pre>
  <p>Where $uriHangouts is the webhook address and the $body is message according to the schema provided here:
  <a href="https://developers.google.com/hangouts/chat/reference/message-formats/basic" rel="nofollow noreferrer">https://developers.google.com/hangouts/chat/reference/message-formats/basic</a></p>
  <p>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:</p>
  <pre><code>[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
  </code></pre>
  <p>I'm literally out of ideas where to go next.</p>
  <p>Please, help!
  Thank you in advance!</p>