有没有办法检查当前是否导入PFX证书而未获取密码

时间:2017-05-11 07:33:39

标签: windows powershell ssl-certificate

我有以下脚本来安装PFX文件:

$cert = Get-ChildItem -Path .\secrets\certificates\ssl\certificate.pfx 
while($true){
    write-host "Enter Password" -foregroundcolor yellow
    try{
        $pass = read-host -AsSecureString
        $cert | Import-PfxCertificate -CertStoreLocation Cert:\CurrentUser\My `
             -Exportable `
             -Password $pass
        break
    }catch{
        write-host "Incorrect password" -foregroundcolor red
        continue

    }

}
write-host "Certificate installed" -foregroundcolor green

但是我希望能够再次运行安装脚本,如果已经安装了证书,那么我不想再次要求用户查找密码。这很乏味。

有没有办法检查PFX文件是否已经导入而没有要求输入密码?然后我可以将我的代码更改为

function Is-PfxInstalled($cert) {

    // ???????

}


$cert = Get-ChildItem -Path .\secrets\certificates\ssl\certificate.pfx 
if(!($cert | Is-Pfx-Installed)
{
    while($true){
        write-host "Enter Password" -foregroundcolor yellow
        try{
            $pass = read-host -AsSecureString
            $cert | Import-PfxCertificate -CertStoreLocation Cert:\CurrentUser\My `
                 -Exportable `
                 -Password $pass
            break
        }catch{
            write-host "Incorrect password" -foregroundcolor red
            continue

    }

}
write-host "Certificate installed" -foregroundcolor green
}

1 个答案:

答案 0 :(得分:0)

如果您知道证书的指纹,则可以使用Test-Path cmdlet检查证书是否已安装。

注意:我将您的功能重命名为Test-CertificateIsInstalled,因为测试批准的动词

function Test-CertificateIsInstalled 
{
    Param
    (
        [string]$Thumbprint,
        [string]$Location = 'Cert:\CurrentUser\My\'
    )

    Test-Path (Join-Path $Location $Thumbprint)
}

该函数使用Cert:\CurrentUser\My作为默认位置,但您可以指定其他位置。用法示例:

Test-CertificateIsInstalled 007790F6561DAD89B0BCD85585762495E358F8A2