PowerShell Basics: Retrieving Azure Key Vault Certificate

Microsoft's Azure Key Vault manages cryptographic keys and certificates used by cloud applications and services.
Some instances may require the use of said certificate stored in Azure Key Vault on a computer, or some hosted service. Use of PowerShell is the quickest way to accomplish this via the following steps:

With the Azure PowerShell tools installed and logged into Azure enter the following:

 Install-Module -Name AzureRm -Repository PSGallery -Scope CurrentUser -Force
Import-Module AzureRm
Login-AzureRmAccount

Next step is to download the certificate. Enter the following:

 $cert = Get-AzureKeyVaultSecret -VaultName 'My-Vault' -Name 'My-Cert'

Once downloaded, the SecretValueText property needs to be converted into a certificate. Enter the following to complete this:

 $certBytes = [System.Convert]::FromBase64String($cert.SecretValueText)
$certCollection = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection
$certCollection.Import($certBytes,$null,[System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable)

The SecretValueText can be converted into bytes and can utilize 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).

 $protectedCertificateBytes = $certCollection.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Pkcs12, $password)
$pfxPath = "D:\a\1\temp\ThomasRayner-export.pfx"
[System.IO.File]::WriteAllBytes($pfxPath, $protectedCertificateBytes)

The first line here exports the certificate and protects it with a password. 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.

 $password = (Get-AzureKeyVaultSecret -VaultName 'My-Vault' -Name 'My-PW').SecretValueText
$secure = ConvertTo-SecureString -String $password -AsPlainText -Force

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

 Import-PfxCertificate -FilePath "D:\a\1\temp\ThomasRayner-export.pfx" Cert:\CurrentUser\My -Password $secure

Be sure to clean up your certificates when completed.