Invoke-RestMethod – Could not establish trust relationship for the SSL/TLS secure channel

Just sharing another TIP from our real-world experience that we have gathered from one of the automation where we are using REST API to perform some operations.

On connecting the rest API using Invoke-Restmethod PowerShell we were getting error:

 

The underlying connection was closed – Could not establish trust relationship for the SSL/TLS secure channel

 

This is occurring because site itself has certificate issues and is hosted out of internal CA, rather than third-party CA.

To resolve this issue with PowerShell there are two solutions that we have found, we are using the later one but both of them works.

 

      1. ADD the following line to your code before the Invoke-RestMethod.

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


      2. Another option is to utilize newer version of PowerShell i.e. pwsh

With newer version of PowerShell i.e., PowerShell core pwsh there is a parameter -SkipCertificateCheck has been added to Invoke-Restmethod

This can be utilized in these situations.

Our version is: PowerShell 7.2.6

Here is the example command:


Invoke-RestMethod -SkipCertificateCheck 'https://10.10.10.10:8443/oauth/token' -Method 'POST' -Headers $headers -Body $body


If you are also facing this same issue, above TIP will save you lot of your time.

 

 

Thanks for reading ….

Tech Wizard

 

https://techwizard.cloud

https://syscloudpro.com/

PowerShell Fast Track

 

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s