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

PowerShell error – The underlying connection was closed: An unexpected error occurred on a send, while trying to run CSOM PowerShell code on SharePoint online sites.

The underlying connection was closed. PowerShell connection error

Same error while trying to use PnP cmdltes

The underlying connection was closed. PnP connection error

From network trace we are able to figure out that server is closing the TCP connection forcefully.

TCP error

Reason being a mismatch in security protocol. Microsoft announced that they will be moving to TLS 1.2 for encryption on October 31, 2018 for Office 365. Here is a Microsoft support article Preparing for the mandatory use of TLS 1.2 in Office 365 explaining this.

Resolution:

Update your default security protocol to be TLS 1.2+. As an immediate fix you can add

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

this to the top of your script to force the PowerShell session to use TLS 1.2 protocol. Remember that this holds good only for the current session. If you close and reopen a new PowerShell it will default to old protocol. You need to add this line of code for every session to get over this problem.TLS 1.2

Your PowerShell CSOM should start working again!