Wednesday, July 3, 2013

Importing a PFX file with PowerShell

The PFX format is great because it includes a certificate and the private key as a single package.

This lets you create a certificate on one machine and then replicate that around for a number of purposes.

Now, this is not the first PowerShell script that handles PFX files.  But one problem that I have found with many is that they are functions and can’t just run on their own and they don’t actually import the private key!

Here is a simple script that you can execute and it checks its execution location for any PFX files and prompts the person running the script for the password to the PFX file.

The assumption is that the PFX file needs to be in the LocalMachine Personal ( or Root) store.

"Looking for included *.pfx.."
$certFile = get-childitem | where {$_.Extension -match "pfx"}
if ($certFile -ne $NULL) {
    "Discovered a .pfx. Installing " + $certFile.Name + " in the LocalMachine\My certificate store.."
    $pfxPwd = Read-Host -Prompt "Please enter the password for your PFX file " -AsSecureString
    $pfxCert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($certFile.FullName, $pfxPwd, "Exportable,PersistKeySet")
    $store = get-item Cert:\LocalMachine\My
    $store.Open("MaxAllowed")
    $store.Add($pfxcert)
    $store.Close()
}

 

BTW – I have been sitting on this post for a really long time.  I just found it in my drafts.


No comments: