title: Automate export x509 certificate w/chain from Server 2008 R2 to a p7b file WITHOUT external tools?
body: <p>I manage the Domain Controllers centrally, but the site admins manage their own digital senders locally. I can easily export an X509 certificate (private key not needed) with the whole chain from a Windows Server 2008 R2 Domain Controller to a p7b file through the wizard:</p>
  
  <p>~~~~~~~~~~~~~~~~~</p>
  
  <p>...5. The Certificate Export Wizard opens. Click Next.</p>
  
  <ol start="6">
  <li><p>In the Export File Format dialog box, do the following:</p>
  
  <p>a. Select Cryptographic Message Syntax Standard – PKCS #7 Certificates (.P7B).</p>
  
  <p>b. Check Include all certificates in the certification path if possible.</p>
  
  <p>c. Click Next.</p></li>
  <li><p>In the File to Export dialog box, click Browse.</p></li>
  <li><p>In the Save As dialog box, do the following:</p>
  
  <p>a. In the File Name box, type ciroots.p7b.</p>
  
  <p>b. In the Save as type box, select PKCS #7 Certificates (*.p7b).</p>
  
  <p>c. Click Save.</p></li>
  <li><p>In the File to Export dialog box, click Next.</p></li>
  <li><p>On the Completing the Certificate Export Wizard page, click Finish.</p></li>
  </ol>
  
  <p>~~~~~~~~~~~~~~~~~</p>
  
  <p>It works great. The resulting file imports just fine into a digital sender for authentication. It gives the site admins access to the other certs in the chain if they have not already imported them. It does not need to contain the private key, since it works fine without it. </p>
  
  <p>The trouble is, I would need to do this manually, literally dozens of times, once for each business site, since each has their own Domain Controllers, each with their own certificate. There must be a way I can automate this certificate export (PowerShell w/.NET, certutil.exe, etc.). Maybe something that uses System.Security.Cryptography.X509Certificates X509IncludeOption with WholeChain, but I can't get it to work: </p>
  
  <p>$Cert = (dir Cert:\localmachine\my)[0]</p>
  
  <p># PKCS7 cert export with .p7b file extension.</p>
  
  <p>$CertCollection = New-Object </p>
  
  <p>System.Security.Cryptography.X509Certificates.X509Certificate2Collection</p>
  
  <p>$Cert | %{[void]$CertCollection.Add($_)}</p>
  
  <p>$Exported_pkcs7 = $CertCollection.Export('Pkcs7')</p>
  
  <p>$out_FileName = $ENV:COMPUTERNAME + ".p7b"</p>
  
  <p>$My_Export_Path = 'd:\CertFiles\' +  $out_FileName</p>
  
  <p>Set-Content -path $My_Export_Path -Value $Exported_pkcs7 -encoding Byte</p>
  
  <p>With this code, I only get the certificate, not the rest of the certificates in its chain. I don't need the whole script, just the part that duplicates the export w/chain that I can already do manually through the GUI. </p>