Loading PFX Certificate Unattendedly

by Nov 4, 2022

PowerShell comes with a cmdlet named Get-PfxCertificate that you can use to load a certificate plus private key into memory. However, if the certificate is password-protected, there is a mandatory prompt to enter the password. You cannot submit the password via parameter, so the cmdlet cannot be used unattendedly.

Here is an alternative function that allows to enter the password via parameter, thus allowing to load pfx certificates on the fly in an unattended manner:

function Get-PfxCertificateUnattended
  # get clear text password
  $plaintextPassword = [PSCredential]::new("X", $Password).GetNetworkCredential().Password
  $container = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection
  $container.Import($FilePath, $plaintextPassword, 'PersistKeySet')

Note that the function always returns the first certificate found in the pfx file. If your pfx files contain more than one certificate, you may want to adjust the index in the last code line.

Twitter This Tip! ReTweet this Tip!