Azure-Connection.psm1
<#
.SYNOPSIS Connects to Azure and sets the provided subscription. .PARAMETER SubscriptionId ID of subscription to use .PARAMETER AutomationConnection Azure automation connection object for using a AA run as account .PARAMETER AzureEnvironment Azure environment to connect to #> function Set-AzureConnection { [CmdletBinding()] Param ( [parameter(mandatory = $true)] $SubscriptionId, $AutomationConnection, $AzureEnvironment = 'AzureCloud' ) $context = $null try { $context = Get-AzureRmContext -ErrorAction Stop } Catch { Write-Verbose "Caller is not logged on to Azure, will try to logon user." } if($null -eq $context.Account) { $envARM = Get-AzureRmEnvironment -Name $AzureEnvironment if($null -ne $AutomationConnection) { $context = Add-AzureRmAccount ` -ServicePrincipal ` -Tenant $Conn.TenantID ` -ApplicationId $Conn.ApplicationID ` -CertificateThumbprint $Conn.CertificateThumbprint ` -Environment $envARM } else # if no connection info, log in using the web prompts { $context = Add-AzureRmAccount -Environment $envARM -ErrorAction Stop } } $null = Set-AzureRmContext -SubscriptionId $SubscriptionId -ErrorAction Stop } <# .SYNOPSIS Connects to Azure and sets the provided subscription using the Azure CLI. .PARAMETER SubscriptionId ID of subscription to use .PARAMETER AzureEnvironment Azure environment to connect to #> function Set-AzCliConnection { Param ( [parameter(mandatory = $true)] $SubscriptionId, $AzureEnvironment = 'AzureCloud' ) $output = az account show *>&1 $errorOutput = $output.Where{$_ -is [System.Management.Automation.ErrorRecord]} if($errorOutput.Count -gt 0) { if($errorOutput[0].Exception.Message -eq "ERROR: Please run 'az login' to setup account.") { az cloud set --name $AzureEnvironment $null = az login --use-device-code } } az account set --subscription $SubscriptionId } |