Unexpected error occurred running a simple unauthorized Rest query Unexpected error occurred running a simple unauthorized Rest query powershell powershell

Unexpected error occurred running a simple unauthorized Rest query


Using:

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

Taken from Powershell 3.0 Invoke-WebRequest HTTPS Fails on All Requests.


in my case the TLS trick did not work, this seems to be a bug in powershell. you need to add the callback using .net code instead of a scriptblock.

#C# class to create callback$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 classAdd-Type -TypeDefinition $code#disable checks using new class[System.Net.ServicePointManager]::ServerCertificateValidationCallback = [SSLHandler]::GetSSLHandler()#do the requesttry{    invoke-WebRequest -Uri myurl -UseBasicParsing} catch {    # do something} finally {   #enable checks again   [System.Net.ServicePointManager]::ServerCertificateValidationCallback = $null}


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

Works in Windows server 2016

Major Minor Build Revision


5 1 17763 1007