Powershell – Install – Import PFX Certificate to separate local account’s Personal store – Automated

certificatepowershell

I've been wrapping my head around automating a way to perform this task:

We deploy Windows Server 2008 R2 images for our customers. We use PowerShell (version 2) to deploy our proprietary software and make various other changes to the system before shipping. This PowerShell process is run under the local Administrator account until it finishes and disables the local Administrator account.

Now, to the issue – I'm trying to install a .PFX client certificate to a SEPARATE user's CurrentUser\My certificate store. Let's call that user "SQL".

Right now the certificate is getting installed under the LocalMachine\My certificate store but one of our development teams have concerns on that position and would like to replicate the original setup.

Now, I know how to get this done dirty by adding in a reboot-step to our deployment script and having this performed under the "SQL" user but I would like to avoid that as it seems like there has to be a way to get this done while under another account. Here's the basic code we're using now to install the certificate to the LocalMachine\My store. Assume $certPath is the path to the .pfx and $pfxPass is the .pfx's password.

function Import-PfxCertificate {
param([string] $certPath, [string]$pfxPass)

$pfx = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$pfx.Import([string]$certPath, [string]$pfxPass, "Exportable,PersistKeySet")

$store = New-Object System.Security.Cryptography.X509Certificates.X509Store("My", "LocalMachine")
$store.open("MaxAllowed")
$store.add($pfx)
$store.close()
}    

Best Answer

I do a similar thing for my servers, but I'm not using pure PowerShell:

psexec.exe -accepteula -u sql -p sqlspassword certutil.exe -p certpassword -importPFX cert.pfx

This just runs the certutil command under the specified account, you need to download psexec.exe,