Output Certificate Chain from PowerShell

I often come across issues where I’m trying to validate a certificate chain of a request but don’t have access to OpenSSL to inspect the certificate returned from a website. Since all Windows OSes contain PowerShell I came up with this script to show the full certificate chain. Using the ServerCertificateValidationCallback set to true we can bypass the typical certificate validation checks in a scenario that we are debugging a problem where the client is reporting an invalid certificate.

[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
$url = "https://microsoft.com:443"
$WebRequest = [Net.WebRequest]::CreateHttp($url)
$WebRequest.AllowAutoRedirect = $true
$chain = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Chain
[Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}

#Request website
try {$Response = $WebRequest.GetResponse()}
catch {}

#Creates Certificate
$Certificate = $WebRequest.ServicePoint.Certificate.Handle
$Issuer = $WebRequest.ServicePoint.Certificate.Issuer
$Subject = $WebRequest.ServicePoint.Certificate.Subject

#Build chain
$chain.Build($Certificate)
$chain.ChainElements.Certificate     

Output: