Export Certificate with private key including all certificates in path using powershell

邮差的信 提交于 2019-12-04 09:19:37

Udpated script to export all certificates matching a particular name and issuer (along with the private key). Make sure you run this with admin priviliges

# 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
}

Updates from your scrip

  • For the check $_.Issuer -eq "CN=$RootCertName" to work you will have to include OU, O, S information as well so for it to work correctly so I modified it to be $_.Issuer -Like "CN=$RootCertName*" so that it matches all Issuer's who's name starts with variable $RootCertName
  • Using $CertToExport.Subject.ToString().Replace("CN=","") for generating pfx file name will cause the name to be of the format some-cert-name, OU=sometext, O=org, C=country.pfx so it is better to restrict upt o the next comma (,) so I added $DestCertName.Substring(0, $DestCertName.IndexOf(","))
  • Finally using Export-PfxCertifcate to export with private key
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!