使用Powershell导出包含私钥的证书,包括路径中的所有证书

Vis*_*hnu 5 powershell certificate windows-server-2012-r2

我正在使用Power Shell脚本来导出带有私钥的证书,该私钥还包括路径中的所有证书。我为此写了一个脚本,它不包含路径中的证书或根证书。下面是脚本。如果我的脚本有任何更改,请建议我。提前致谢。

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

deg*_*ant 5

修改后的脚本可导出与特定名称和颁发者匹配的所有证书(以及私钥)。确保使用管理员权限运行此程序

# Script to export certificate from LocalMachine store along with private key
$Password = "@de08nt2128"; #password to access certificate after expting
$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
}
Run Code Online (Sandbox Code Playgroud)

您的股票的更新

  • 为了使支票$_.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所以最好限制UPTØ下一逗号(,),所以我加入$DestCertName.Substring(0, $DestCertName.IndexOf(","))
  • 最后Export-PfxCertifcate用于导出私钥