Getting An SSL Web Page’s Certificate

When it comes time to rolling SSL certificates on web servers, nothing beats checking the server to see what is actually being served.

Get-SslWebPage outlook.com

Url CertName Expires
--- -------- -------
https://outlook.com:443/        outlook.com 4/17/2014 2:26:21 PM

 

Get-SslWebPage outlook.com -full

Url : https://outlook.com:443/
WebRequestObject : System.Net.HttpWebRequest
WebResponseObject : System.Net.HttpWebResponse
CertObject : System.Security.Cryptography.X509Certificates.X509Certificate
CertName : outlook.com
Expires : 4/17/2014 2:26:21 PM
Content :

 

 

 

function Get-SslWebPage {
     param (
         [Parameter(
             Position = 0, 
             Mandatory = $true, 
             ValueFromPipeline = $true,
             ValueFromPipelineByPropertyName = $true
         )] [String[]]$computer,
         [string]$url = $null,
         [int]$port = 443,
         [int]$Timeout = 10,
         [switch]$full
     );
    
     process {
         foreach ($myComputer in $computer) {
             $myComputer = $myComputer -replace "^https://";
             $ConnectString = "https://$myComputer`:$port/$url";
             Write-Verbose "Connect String: '$connectString'";
             $WebRequest = [Net.WebRequest]::Create($ConnectString)
             $WebRequest.Timeout = $Timeout * 1024;
             $WebRequest.AllowAutoRedirect = $false;
             [Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
             try { $webResponse = $WebRequest.GetResponse(); }
             catch { continue; }
             if ($webResponse) {
                 $output = $webResponse | Select-Object -Property @{
                     n = 'Url';
                     e = { $ConnectString; }
                 }, @{
                     n = 'WebRequestObject';
                     e = { $WebRequest; }
                 }, @{
                     n = 'WebResponseObject'; 
                     e = { $webResponse; }
                 }, @{
                     n = 'CertObject';
                     e = { $webRequest.ServicePoint.Certificate; }
                 }, @{
                     n = 'CertName';
                     e = { $webRequest.ServicePoint.Certificate.Subject -replace ",.*" -replace "^.*="; }
                 }, @{
                     n = 'Expires';
                     e = {
                     ([System.Security.Cryptography.X509Certificates.X509Certificate2]$webRequest.ServicePoint.Certificate).NotAfter }
                 }, @{
                     n = 'Content';
                     e = { ([IO.StreamReader]$webResponse.GetResponseStream()).ReadToEnd(); }
                 };
                 if ($full) {
                     $output;
                 } else {
                     $output | Select-Object -Property Url, CertName, Expires;
                 }
             } else {
                 Write-Warning "Unable to connect to $connectString"
             }
         }
     }
}