Disabling SSL Certificate Validation with PowerShell

I’ve run into this issue about a billion times.  Mostly, I see it when I’m coding against a web API on a device with a bad or partially-valid self-signed cert.

I’ve seen several articles on how to disable the SSL validation check, but have had only limited success with them.  I finally found an approach out there that works for all of my use cases, and wrapped a nice function around it.  I’m publishing it here in hopes it helps people out someday.

Basically, call this either to enable or disable SSL certificate validation.  It is safe to run multiple times in the same session and doesn’t throw any errors.

Here it is:

function Set-SslCertificateValidation
{
<#
.SYNOPSIS
This function enables or disables SSL Cert validation in your PowerShell session. Calling this affects SSL validation for ALL function calls in the session!
.PARAMETER Disable
If specified, validation is disabled. If not specified (the default) validation is re-enabled.
.EXAMPLE
Set-SslCertificateValidation -Disable
# Disables SSL Cert validation
.EXAMPLE
Set-SslCertificateValidation
# Re-enables SSL Cert validation again
#>
param
(
[switch] $Disable
)
$type = [AppDomain]::CurrentDomain.GetAssemblies().ExportedTypes | Where-Object { $_.Name -ieq "TrustAllCertsPolicy" }
if ( !$type )
{
# Disable SSL Certificate validation:
Add-Type -TypeDefinition @"
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;
}
}
"@
}
if ( $Disable )
{
[System.Net.ServicePointManager]::CertificatePolicy = New-Object -TypeName TrustAllCertsPolicy
}
else
{
[System.Net.ServicePointManager]::CertificatePolicy = $null
}
}

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 )

Google photo

You are commenting using your Google 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