PowerShell Get Certificate Thumbprint with Password PFX File

flipcode picture flipcode · Nov 12, 2014 · Viewed 22.8k times · Source

I'm trying to get the thumbprint of a password protected pfx file using this code:

function Get-CertificateThumbprint {
    # 
    # This will return a certificate thumbprint, null if the file isn't found or throw an exception.
    #

    param (
        [parameter(Mandatory = $true)][string] $CertificatePath,
        [parameter(Mandatory = $false)][string] $CertificatePassword
    )

    try {
        if (!(Test-Path $CertificatePath)) {
            return $null;
        }

        if ($CertificatePassword) {
            $sSecStrPassword = ConvertTo-SecureString -String $CertificatePassword -Force –AsPlainText
        }

        $certificateObject = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
        $certificateObject.Import($CertificatePath, $sSecStrPassword);

        return $certificateObject.Thumbprint
    } catch [Exception] {
        # 
        # Catch accounts already added.
        throw $_;
    }
}

When I run it, I get this error:

Cannot find an overload for "Import" and the argument count: "2".
At C:\temp\test.ps1:36 char:9
+         $certificateObject.Import($CertificatePath, $sSecStrPassword);
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodCountCouldNotFindBest

Can someone please help me sort this out?

Thanks All. :-)

Answer

Nikita G. picture Nikita G. · Oct 7, 2015

According to this SuperUser response, in PS 3.0 there is Get-PfxCertificate command to do that:

 Get-PfxCertificate -FilePath Certificate.pfx