使用PowerShell导出包含私钥和路径中所有证书的证书

11

我正在编写PowerShell脚本以导出带有私钥的证书,其中还包括路径中的所有证书。我已经为此编写了一个脚本,但它不包括路径中或根证书中的证书。以下是我的脚本。如果需要修改,请提供建议。 感谢您的帮助。

$Password="@de08nt2128"; #password to access certificate after expting
$CertName="WMSvc-WIN-9KC7DG31JBV"; # name of the certificate to export
$RootCertName="WMSvc-WIN-9KC7DG31JBV"; # root certificate

$DestCertName="testcert"
$ExportPathRoot="C:\DestinationFolder"

$CertListToExport=Get-ChildItem -Path cert:\LocalMachine\My | ?{ $_.Subject -Like "*CN=$CertName*" -and $_.Issuer -eq "CN=$RootCertName" }

foreach($CertToExport in $CertListToExport | Sort-Object Subject)
{
    $DestCertName=$CertToExport.Subject.ToString().Replace("CN=","");

    $CertDestPath=Join-Path -Path $ExportPathRoot -ChildPath "$DestCertName.pfx"

    $type = [System.Security.Cryptography.X509Certificates.X509Certificate]::pfx
    $SecurePassword = ConvertTo-SecureString -String $Password -Force –AsPlainText

    $bytes = $CertToExport.export($type, $SecurePassword)
    [System.IO.File]::WriteAllBytes($CertDestPath, $bytes)

}
"Completed" 
1个回答

12

更新脚本,以导出与特定名称和颁发者匹配的所有证书(连同私钥)。确保您使用管理员权限运行此脚本:

# Script to export certificate from LocalMachine store along with private key
$Password = "@de08nt2128"; #password to access certificate after exporting
$CertName = "WMSvc-WIN-9KC7DG31JBV"; # name of the certificate to export
$RootCertName = "WMSvc-WIN-9KC7DG31JBV"; # root certificate (the Issuer)
$ExportPathRoot = "C:\DestinationFolder"

$CertListToExport = Get-ChildItem -Path cert:\LocalMachine\My | ?{ $_.Subject -Like "*CN=$CertName*" -and $_.Issuer -Like "CN=$RootCertName*" }

foreach($CertToExport in $CertListToExport | Sort-Object Subject)
{
    # Destination Certificate Name should be CN. 
    # Since subject contains CN, OU and other information,
    # extract only upto the next comma (,)
    $DestCertName=$CertToExport.Subject.ToString().Replace("CN=","");
    $DestCertName = $DestCertName.Substring(0, $DestCertName.IndexOf(","));

    $CertDestPath = Join-Path -Path $ExportPathRoot -ChildPath "$DestCertName.pfx"

    $SecurePassword = ConvertTo-SecureString -String $Password -Force -AsPlainText

    # Export PFX certificate along with private key
    Export-PfxCertificate -Cert $CertToExport -FilePath $CertDestPath -Password $SecurePassword -Verbose
}

来自您的脚本更新

  • 为了使检查$_.Issuer -eq "CN=$RootCertName"正常工作,您必须包括OU、O、S信息,因此我修改为$_.Issuer -Like "CN=$RootCertName*",以便匹配所有以变量$RootCertName开头的颁发者的名称
  • 使用$CertToExport.Subject.ToString().Replace("CN=","")生成pfx文件名将导致名称格式为some-cert-name, OU=sometext, O=org, C=country.pfx,因此最好仅限制到下一个逗号(,),所以我添加了$DestCertName.Substring(0, $DestCertName.IndexOf(","))
  • 最后使用Export-PfxCertifcate 导出带有私钥

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接