title: PowerShell Import Pfx, and Private Key "Lost"
body: <p>I used following PowerShell function to import PFX to my Windows 2008 R2 server's certificate store</p>
  
  <pre><code>function Import-PfxCertificate ([String]$certPath,[String]$certificateStoreLocation = "CurrentUser",[String]$certificateStoreName = "My",$pfxPassword = $null)
  {
      $pfx = new-object System.Security.Cryptography.X509Certificates.X509Certificate2    
  
      $pfx.Import($certPath, $pfxPassword, "Exportable,PersistKeySet")    
  
      $store = new-object System.Security.Cryptography.X509Certificates.X509Store($certificateStoreName,$certificateStoreLocation)    
      $store.open("MaxAllowed")    
      $store.add($pfx)    
      $store.close()
      return $pfx
  }
  </code></pre>
  
  <p>The caller of the function looks like <code>$importedPfxCert = Import-PfxCertificate $pfxFile "LocalMachine" "My" $password</code> I installed it to local machine's My store. Then I granted read permission to my IIS Application pool.</p>
  
  <p>I have a WCF service which needs to use it</p>
  
  <pre><code>&lt;behaviors&gt;
    &lt;serviceBehaviors&gt;
      &lt;behavior&gt;
        &lt;serviceCredentials&gt;
          &lt;serviceCertificate findValue="MyCertName" x509FindType="FindBySubjectName" /&gt;
          &lt;userNameAuthentication userNamePasswordValidationMode="Custom"
            customUserNamePasswordValidatorType="MyValidator" /&gt;
        &lt;/serviceCredentials&gt;
      &lt;/behavior&gt;
    &lt;/serviceBehaviors&gt;
  &lt;/behaviors&gt;
  </code></pre>
  
  <p>When I use a client to call the service, I got exception from WCF <code>It is likely that certificate 'CN=MyCertName' may not have a private key that is capable of key exchange or the process may not have access rights for the private key.</code></p>
  
  <p>If I remove it from MMC, and manually import the same PFX file from Certificate MMC, to same store and grant same permission, my client can call the service without problem.</p>
  
  <p>So it leads me to think, for some reason if I use PowerShell the private key is screwed somehow.</p>
  
  <p>The funny thing is in either way, I go to MMC and double click on my installed certificate I can see <code>You have a private key that corresponds to the certificate.</code> so it looks like private key is loaded even in PowerShell. permission settings are identical.</p>
  
  <p>Any clue or experience?</p>