PowerShell Invoke-RestMethod : The underlying connection was closed: An unexpected error occurred on a send

As I’m writing more PowerShell (what I really mean is googling PowerShell or asking Steven @StevenMurawski), I ran into this weird thing. I was trying to hit an Azure Function that I wrote using Invoke-RestMethod and I kept getting the error:

Invoke-RestMethod : The underlying connection was closed: An unexpected error occurred on a send

WTF????? After googling a bunch, turns out this is a TLS issue. PowerShell defaults to TLS1, I needed mine to be at TLS1.2. More googling gave the the fix. Add this before you make your Invoke-RestMethod call

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls -bor [Net.SecurityProtocolType]::Tls11 -bor [Net.SecurityProtocolType]::Tls12

I’m sure i’m gonna run into this again so sticking this in my blog so I’ll find it quickly Smile

One Comment

  1. Even i faced the same issue.

    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
    is worked for me in my local system. But not in VM.

    Tried :
    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Ssl3, [Net.SecurityProtocolType]::Tls, [Net.SecurityProtocolType]::Tls11, [Net.SecurityProtocolType]::Tls12
    $code = @”
    public class SSLHandler
    {
    public static System.Net.Security.RemoteCertificateValidationCallback GetSSLHandler()
    {
    return new System.Net.Security.RemoteCertificateValidationCallback((sender, certificate, chain, policyErrors) => { return true; });
    }

    }
    “@

    #compile the class
    Add-Type -TypeDefinition $code

    #disable checks using new class
    [System.Net.ServicePointManager]::ServerCertificateValidationCallback = [SSLHandler]::GetSSLHandler()
    try{
    invoke-restmethod -uri $url -method GET
    }
    catch{
    }
    finally{
    #enable checks again
    [System.Net.ServicePointManager]::ServerCertificateValidationCallback = $null
    }

    This one also not worked….

    finally enabled the firewall on the respective VM which worked for me.

Leave a Reply

Your email address will not be published. Required fields are marked *