7

When I try to use Invoke-WebRequest on https ,I'm getting some weird error:

"Invoke-WebRequest : The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel."

It's My Code:

   [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls
    $url = "https://X.X.X.X:4343/officescan/console/html/cgi/cgiChkMasterPwd.exe"
    $r = Invoke-WebRequest $url -SessionVariable office

Any advice for me ?? Thanks a lot.

Scott Lee
  • 71
  • 1
  • 1
  • 3

2 Answers2

0

Of course it is an issue with an invalid certificate (autosigned?, expired?) if using Powershell 7+ simply use the new parameter

Invoke-WebRequest -Uri 'https://trees.com/' -SkipCertificateCheck

if using Powershell 5.1 it is a bit harder:

$code= @"
        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;
            }
        }
"@
Add-Type -TypeDefinition $code -Language CSharp
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
Invoke-WebRequest -Uri 'https://trees.com/'
Mikel V.
  • 46
  • 6
-2

You can also get that problem if you're using https:// in the Uri and the url is available through http://. More specifically, use

Invoke-WebRequest -Uri 'https://trees.com/'

and will get the following error

Invoke-WebRequest : The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.

It doesn't work

Then, if you use

Invoke-WebRequest -Uri 'trees.com'

or if you use

Invoke-WebRequest -Uri 'http://trees.com'

will work fine

It works

Tiago Martins Peres
  • 12,598
  • 15
  • 77
  • 116