如何使用 powershell 从 Azure keyvault 下载 .cer 格式的证书?

how to download certificate from Azure keyvault in .cer format using powershell?

我想以 .cer 格式从 keyvault 下载证书作为我的自动化脚本的一部分。我将如何使用 powershell 来做到这一点?

如果您想在自动化 Runbook 中将证书下载为 .cer 文件,您可以使用下面的脚本将其下载到临时文件夹 $env:temp.

确保您已经将与 RunAs 帐户相关的服务主体添加到您的密钥库的 Access policies 中,它需要 秘密权限中的 GetGet 证书权限 .

样本:

$connectionName = "AzureRunAsConnection"
try
{
    # Get the connection "AzureRunAsConnection "
    $servicePrincipalConnection=Get-AutomationConnection -Name $connectionName         

    Connect-AzAccount `
        -ServicePrincipal `
        -TenantId $servicePrincipalConnection.TenantId `
        -ApplicationId $servicePrincipalConnection.ApplicationId `
        -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint 
}
catch {
    if (!$servicePrincipalConnection)
    {
        $ErrorMessage = "Connection $connectionName not found."
        throw $ErrorMessage
    } else{
        Write-Error -Message $_.Exception
        throw $_.Exception
    }
}

$cert = Get-AzKeyVaultCertificate -VaultName "joykeyvault" -Name "test1234"
$secret = Get-AzKeyVaultSecret -VaultName "joykeyvault" -Name $cert.Name

$secretByte = [Convert]::FromBase64String($secret.SecretValueText)
$x509Cert = new-object System.Security.Cryptography.X509Certificates.X509Certificate2
$x509Cert.Import($secretByte, "", "Exportable,PersistKeySet")

$cer = Export-Certificate -Cert $x509Cert -FilePath $env:temp\test.cer
Write-Output $cer