首页 > 解决方案 > Import-PfxCertificate 无操作,但没有错误或任何东西

问题描述

我正在尝试将 PFX 文件导入本地证书存储。但是,Import-PfxCertificate什么都不做。没有返回值,没有错误,什么都没有:

在此处输入图像描述

我可以在资源管理器中双击 PFX 文件并使用相同的密码将其导入,这样就可以了。关于 PowerShell CmdLet 的某些内容不起作用。我也尝试过其他商店,例如Cert:\LocalMachine\Myand TrustedPeople。运行它-Verbose -Debug不会显示任何额外内容。应用程序或安全事件日志中也没有任何内容。我也以管理员身份运行。想法?

标签: powershellcertificatewindows-server-2016pfx

解决方案


Pfx 文件可能有一个证书链。将其视为集合将是处理证书存储的更好方法。请参阅为 C#安装证书链,这是基于的;

[string] $certPath = '.\test.pfx';
[string] $certPass = 'MyPassword';

# Create a collection object and populate it using the PFX file
$collection = [System.Security.Cryptography.X509Certificates.X509Certificate2Collection]::new();
$collection.Import($certPath, $certPass,  [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::PersistKeySet);

try {
    # Open the Store My/Personal
    $store = [System.Security.Cryptography.X509Certificates.X509Store]::new('My');
    $store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite);

    foreach ($cert in $collection) {
        Write-Host ("Subject is: '{0}'" -f  $cert.Subject  )
        Write-Host ("Issuer is:  '{0}'" -f  $cert.Issuer  )

        # Import the certificate into an X509Store object
        # source https://support.microsoft.com/en-au/help/950090/installing-a-pfx-file-using-x509certificate-from-a-standard-net-applic

        if ($cert.Thumbprint -in @($store.Certificates | % { $_.Thumbprint } )) {
            Write-Warning "Certificate is already in the store"
            # Force the removal of the certificate so we have no conflicts, not required if this is the first install    
            $store.Remove($cert)
        }
        # Add in the certificate 
        $store.Add($cert);
    }
} finally {
    if($store) {
        # Dispose of the store once we are done
        $store.Dispose()
    }
}

推荐阅读