如何在带有AutomationConnection的Powershell Runbook中使用Connect-AzAccount

时间:2019-04-29 18:52:34

标签: powershell azure-automation azure-runbook azure-rm

我可以找到的用于验证Runbook的所有示例均使用AzureRM模块:

$connectionName = "AzureRunAsConnection"
$servicePrincipalConnection=Get-AutomationConnection -Name $connectionName         
Add-AzureRmAccount `
        -ServicePrincipal `
        -TenantId $servicePrincipalConnection.TenantId `
        -ApplicationId $servicePrincipalConnection.ApplicationId `
        -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint 

但是,如果您使用的是新的Az模块,则此代码将不起作用,并且您不能在同一Runbook中混合 AzureRM模块 Az模块。您如何获得身份验证才能与新的Az模块一起使用。

1 个答案:

答案 0 :(得分:1)

此块可用于在Runbook中进行身份验证。 确保遵循模块配置说明: Az module support in Azure Automation

$connectionName = "AzureRunAsConnection"
try
{
    # Get the connection "AzureRunAsConnection "

    $servicePrincipalConnection = Get-AutomationConnection -Name $connectionName

    "Logging in to Azure..."
    $connectionResult =  Connect-AzAccount -Tenant $servicePrincipalConnection.TenantID `
                             -ApplicationId $servicePrincipalConnection.ApplicationID   `
                             -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint `
                             -ServicePrincipal
    "Logged in."

}
catch {
    if (!$servicePrincipalConnection)
    {
        $ErrorMessage = "Connection $connectionName not found."
        throw $ErrorMessage
    } else{
        Write-Error -Message $_.Exception
        throw $_.Exception
    }
}