title: Importing Certificate with private key
body: <p>I am trying to import a certificate with a private key and although my script is "working" it is missing something which I can't seem to figure out. </p>
  
  <p>I have an app which talks to KeyVault and uses this certificate for authorization. I have the password for said certificate and when I install the <code>PFX</code> manually along with assigning the <code>NETWORK SERVICE</code> account permission this works fine. However, using the following PowerShell I get the error <code>Keyset does not exist</code>. Everything seems normal when I check this under cert manager. Clearly, the UI is doing something different.. any ideas?</p>
  
  <p><em>EDIT</em>
  When I add the <code>NETWORK SERVICE</code> account manually this works fine. PowerShell is running in admin mode when I execute the script so perhaps its some weirdness in that? </p>
  
  <p>The script</p>
  
  <pre><code>cls
  $certName = "certname.pfx"
  $path = "C:\Certificates\$certName"
  $serviceAccount = 'NETWORK SERVICE'
  $permissionType = 'Read'
  $password = 'somepassword'
  
  try {
      # Import the certificate maintaining the private key format
      $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
      $cert.Import($path, $password, [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]"PersistKeySet")
  
      # Add the cert to personal store location
      $store = Get-Item Cert:\LocalMachine\My
      $store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]"ReadWrite")
      $store.Add($cert)
      $store.Close()
  
      # Get SecurityIdentifier value from current username
      $currentUser = New-Object System.Security.Principal.NTAccount($env:USERNAME)
      $strSID = $currentUser.Translate([System.Security.Principal.SecurityIdentifier])
      $path = "$env:USERPROFILE\AppData\Roaming\Microsoft\Crypto\RSA\$($strSID.Value)\$($cert.PrivateKey.CspKeyContainerInfo.UniqueKeyContainerName)"
      $acl = Get-Acl $path
      $rule = New-Object Security.AccessControl.FileSystemAccessRule $serviceAccount, 'FullControl', Allow
      $acl.AddAccessRule($rule)
      Set-Acl $path $acl
  
      Write-Host "Cert installed, press any key to continue" -ForegroundColor Green
      Read-Host
  }
  catch {
      Write-Error -Message $_
  }
  </code></pre>
  
  <p><strong>ANSWER</strong>
  For others experiencing the same issues as I was, simply provide multiple storage flags:</p>
  
  <pre><code>$flags = @([System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]"MachineKeySet", [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]"PersistKeySet")
  $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
  $cert.Import($path, $password, $flags)
  </code></pre>