Ignore self-signed certificates in PowerShell

When using windows PowerShell as REST client, you may encounter certificate invalid issues for various reasons. The most likely reason should be a self-signed certificate or a invalid common name certificate or sometimes not adding SAN names in the certificates. This may cause your script to break if it relies on fetching data from remote server when communicating on HTTPS.

To avoid SSL Certificate trust issues if using HTTPS, we can use below PowerShell function to help:

function Ignore-SelfSignedCerts
{
    try
    {
        Write-Host "Adding TrustAllCertsPolicy type." -ForegroundColor White
        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;
            }
        }
        "@
        Write-Host "TrustAllCertsPolicy type added." -ForegroundColor White
      }
    catch
    {
        Write-Host $_ -ForegroundColor "Yellow"
    }
    [System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
}

In last, we just need to call the function using function name. When you call the URL, you won’t have an error now. You will be ignoring SSL trust and ignoring safe header parsing. Not a best practice but if you know and trust your sources, its good enough.

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 )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s