PowerShell使用密码PFX文件获取证书指纹

fli*_*ode 9 passwords powershell x509certificate2

我正在尝试使用以下代码获取受密码保护的pfx文件的指纹:

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 $_;
    }
}
Run Code Online (Sandbox Code Playgroud)

当我运行它时,我收到此错误:

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
Run Code Online (Sandbox Code Playgroud)

有人可以帮我解决这个问题吗?

谢谢大家.:-)

Nik*_* G. 30

根据这个SuperUser响应,在PS 3.0中有Get-PfxCertificate命令来执行此操作:

 Get-PfxCertificate -FilePath Certificate.pfx 
Run Code Online (Sandbox Code Playgroud)

  • Get-PfxCertificate没有密码参数.如果您需要以非交互模式导入证书,请参阅kyorilys的答案. (4认同)

kyo*_*lys 13

你可以这样做

$certificateObject = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$certificateObject.Import($CertificatePath, $sSecStrPassword, [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::DefaultKeySet)
return $certificateObject.Thumbprint
Run Code Online (Sandbox Code Playgroud)

请记住设置这两个变量:$ CertificatePath和$ sSecStrPassword

  • 在新版本上,您应该使用 $certificateObject = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($CertificatePath, $sSecStrPassword) (2认同)

Kei*_*ill 4

PowerShell 错误消息是正确的。不存在需要两个参数的重载。根据您使用的参数,我认为您想要需要第三个参数的重载- 枚举 -X509KeyStorageFlags例如

$certificateObject.Import($CertificatePath, $sSecStrPassword, [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::DefaultKeySet)
Run Code Online (Sandbox Code Playgroud)