Last active
October 13, 2022 18:41
-
-
Save pandieme/d810071e5efc90f7f0927c5669c72153 to your computer and use it in GitHub Desktop.
Bypass SSL certificate validation check when using Invoke-WebRequest or Invoke-RestMethod in Windows PowerShell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if ($PSEdition -eq 'Desktop') { | |
class TrustAllCertsPolicy : System.Net.ICertificatePolicy { | |
[bool] CheckValidationResult ( | |
[System.Net.ServicePoint]$srvPoint, | |
[System.Security.Cryptography.X509Certificates.X509Certificate]$certificate, | |
[System.Net.WebRequest]$request, | |
[int]$certificateProblem | |
) { | |
return $true | |
} | |
} | |
[System.Net.ServicePointManager]::CertificatePolicy = New-Object -TypeName TrustAllCertsPolicy | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if ($PSEdition -eq 'Desktop') { | |
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 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using namespace System.Net | |
using namespace System.Security.Cryptography.X509Certificates | |
using namespace System.Management.Automation | |
if ($PSEdition -eq 'Desktop') { | |
class TrustAllCertsPolicy : ICertificatePolicy { | |
[bool] CheckValidationResult ( | |
[ServicePoint]$srvPoint, | |
[X509Certificate]$certificate, | |
[WebRequest]$request, | |
[int]$certificateProblem | |
) { | |
return $true | |
} | |
} | |
[ServicePointManager]::CertificatePolicy = New-Object -TypeName TrustAllCertsPolicy | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I've seen, and used myself, the C# code to define the
TrustAllCertsPolicy
class so much over the years, and it only dawned on me today that this could be done using PowerShell code.Three implementations of the fix are in this gist. The traditional C# method, how I like to do it by defining
using namespace
at the start of my script, and by using the full class names that can be pasted anywhere you need it.