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.

2 thoughts on “Ignore self-signed certificates in PowerShell

Leave a comment