Skip to content

Instantly share code, notes, and snippets.

@pandieme
Last active October 13, 2022 18:41
Show Gist options
  • Save pandieme/d810071e5efc90f7f0927c5669c72153 to your computer and use it in GitHub Desktop.
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
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
}
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
}
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
}
@pandieme
Copy link
Author

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.

Note, that this snippet of code is only required in Windows PowerShell. Since PowerShell 6.0.0, you can append the -SkipCertificateCheck switch to both Invoke-RestMethod and Invoke-WebRequest which achieves the same result.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment