How to resolve - The underlying connection was closed - Could not establish trust relationship for the SSL/TLS secure channel in PowerShell?

PowerShellMicrosoft TechnologiesSoftware & Coding

When you run Invoke-WebRequest or Invoke-RestMethod command, sometimes you get the error “The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.” because there could be a certificate issue or the required windows version doesn’t support the TLS or SSL version. You can use the below command to bypass this error.

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

Or you can use the below code to resolve this error.

Example

add-type @"
   using System.Net;
   using System.Security.Cryptography.X509Certificates;
   public class TrustAllCertsPolicy : ICertificatePolicy {
      public bool CheckValidationResult(
      ServicePoint srvPoint, X509Certificate certificate,
      WebRequest request, int certificateProblem) {
      return true;
   }
}
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
raja
Published on 01-Sep-2021 07:40:52
Advertisements