How To Retrieve A Certificate From Azure Key Vault Via PowerShell

So, you’ve got a certificate stored in Azure Key Vault that you want to download with PowerShell and use on a computer, or some hosted service. How do you get it and actually use it? Well, here, I’ll show you.

First, you’ve got to have the Azure PowerShell tools installed and be logged into Azure (or be running in a way where you’re already authenticated, like in Azure Automation).

Next, it’s time to download the certificate. There are some Azure Key Vault cmdlets built in which, helpfully, do not follow the standard AzureRm naming scheme.

Now, we have to convert the SecretValueText property to a certificate.

We can convert the SecretValueText to bytes, and use the X509Certificate2Collection class to convert those bytes to a certificate.

Next, we want to write the certificate to a pfx file on a disk somewhere (preferably to a temp location you can clean up later in the script).

The first line here exports the certificate and protects it with a password, but where did that come from?! Then it writes the protected bytes to a path on the file system.

So where did that password come from? I’m actually storing that in the Azure Key Vault, too.

Now, I can either refer to that pfx file, or I can import it like this.

Make sure you clean up your certs after you’re done!