Script To Search For Specific Certificate

We had a computer with an expired certificate we could not find, but our monitoring software was alerting on. After some time, we gave up opening each certificate, one by one, to see if the thumbprint matched, and just wrote the script below. It searches through all the certificates on the computer looking for the machine thumbprint.

Just run this script in a PowerShell As An Administrator and change the thumbprint in the first line to the one you want to search for:


$ThumbprintToFind = "BFA4C820FE02AA3D899CB3A734D90D750543F"

# Function to search for a certificate by thumbprint in a specific store
function Get-CertificateByThumbprint {
    param(
        [Parameter(Mandatory=$true)]
        [string]$StoreName,
        [Parameter(Mandatory=$true)]
        [string]$Location,
        [Parameter(Mandatory=$true)]
        [string]$Thumbprint
    )

    Write-Verbose "Searching in $($Location)\$($StoreName) store..." -Verbose
    $Certificate = Get-ChildItem -Path "$Location\$StoreName" | Where-Object {$_.Thumbprint -ceq $Thumbprint}

    if ($Certificate) {
        Write-Host "Found certificate in $($Location)\$($StoreName) store:"
        Write-Host "  Subject: $($Certificate.Subject)"
        Write-Host "  Issuer: $($Certificate.Issuer)"
        Write-Host "  NotBefore: $($Certificate.NotBefore)"
        Write-Host "  NotAfter: $($Certificate.NotAfter)"
        Write-Host "  Thumbprint: $($Certificate.Thumbprint)"
        return $Certificate
    } else {
        Write-Verbose "Certificate with thumbprint '$Thumbprint' not found in $($Location)\$($StoreName) store." -Verbose
        return $null
    }
}

# Define the locations and store names to search
$LocationsToSearch = @("Cert:\CurrentUser", "Cert:\LocalMachine")
$StoresToSearch = @("My", "Root", "CA", "Trust", "AuthRoot", "TrustedPublisher", "ClientAuthIssuer")

# Initialize a flag to track if the certificate was found
$CertificateFound = $false

# Loop through each location and store to find the certificate
foreach ($Location in $LocationsToSearch) {
    foreach ($StoreName in $StoresToSearch) {
        $FoundCert = Get-CertificateByThumbprint -StoreName $StoreName -Location $Location -Thumbprint $ThumbprintToFind.ToUpper()
        if ($FoundCert) {
            $CertificateFound = $true
            # No need to continue searching if found
            break
        }
    }
    if ($CertificateFound) {
        break
    }
}

# Output if the certificate was not found in any of the searched stores
if (-not $CertificateFound) {
    Write-Host "Certificate with thumbprint '$ThumbprintToFind' was not found in any of the common certificate stores."
}

0 Comments

Leave a Reply

Avatar placeholder

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