Use PowerShell to find specific SSL server certificate

This article might be useful if you have list of servers on which you want to make simple scanning for specific SSL certificate. In this example we will search for certificate which name contains word <>token.

Please note that searching criteria should be based on your internal naming convention for certificates.

# Checking hostname of a server provided in input file 
$hostname = ([System.Net.Dns]::GetHostByName("$Server")).hostname
  
# Querying for certificates
$Certs = Invoke-Command $Server -ScriptBlock{ Get-ChildItem Cert:\LocalMachine\My }

# Searching phrase
$CertificateName = "token"

# Display searched certificate
$Array | Where-Object {$_ -like "*$CertificateName*"}

Certificate location (Cert:\LocalMachine\My):

Script can be run also as a verification step after certificate replacement activity.

Output:

Certificate
Certificate

Final script:

    
# Input file
$Servers = Get-Content "C:\users\$env:username\desktop\servers.txt"
$ErrorActionPreference = 'Stop'
$Array = @()

# Searching phrase
$CertificateName = "token"

# Looping each server 
foreach($Server in $Servers)
{   
    Write-Host Processing $Server -ForegroundColor yellow
    
    Try
    {
        # Checking hostname of a server provided in input file 
        $hostname = ([System.Net.Dns]::GetHostByName("$Server")).hostname
  
        # Querying for certificates
        $Certs = Invoke-Command $Server -ScriptBlock{ Get-ChildItem Cert:\LocalMachine\My }
    }
    Catch
    {
        $_.Exception.Message
        Continue
    }
     
    If($hostname -and $Certs)
    {
        Foreach($Cert in $Certs)
        {
            # Adding certificate properties and server name to object
            $Object = New-Object PSObject 
            $Object | Add-Member Noteproperty "Server name" -Value $hostname
            $Object | Add-Member Noteproperty "Certificate name" -Value $cert.dnsnamelist.punycode 
            $Object | Add-Member Noteproperty "Certificate issuer"  -Value $cert.issuer   
            $Object | Add-Member Noteproperty "Certificate expiration date" -Value $cert.notafter  
            $Object | Add-Member Noteproperty "Certificate thumbprint" -Value $cert.thumbprint   
  
            # Adding object to an array
            $Array += $Object
        }
    } 
    Else
    {
        Write-Warning "Something went wrong"
    }
}

If($Array)
{
    # Display searched certificate
    $Array | Where-Object {$_ -like "*$CertificateName*"}
    
    # To export to CSV
    $Array | Where-Object {$_ -like "*$CertificateName*"} | Export-Csv -Path C:\temp\results.csv -Force -NoTypeInformation
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.