Skip to content

Instantly share code, notes, and snippets.

@fslef
Last active June 26, 2023 13:14
Show Gist options
  • Save fslef/b0aa1e9398719d2eac728f8c1cb41fcd to your computer and use it in GitHub Desktop.
Save fslef/b0aa1e9398719d2eac728f8c1cb41fcd to your computer and use it in GitHub Desktop.
Connect-ToAzureSubscription
function Connect-ToAzureSubscription {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true, Position = 0)]
[ValidateNotNullOrEmpty()]
[guid]$TenantId,
[Parameter(Mandatory = $true, Position = 1)]
[ValidateNotNullOrEmpty()]
[guid]$SubscriptionId,
[Parameter(Mandatory = $false, Position = 2)]
[ValidateSet("AzureCloud", "AzureChinaCloud", "AzureUSGovernment")]
[string]$Environment = "AzureCloud"
)
# Check if already connected to the right subscription
$currentSubscription = (Get-AzContext).Subscription.Id
if ($currentSubscription -eq $SubscriptionId) {
Write-Debug "Already connected to the right Azure Context"
return
}
# elseif Is connected to the right tenant but wrong subscription
elseif ((Get-AzContext).Tenant.Id -eq $TenantId) {
Write-Debug "Switching to subscription $($SubscriptionId)"
Set-AzContext -Subscription $SubscriptionId -ErrorAction Stop | Out-Null
}
# else Connect to the right tenant and subscription
else {
Write-Debug "Connecting to tenant $($TenantId) and subscription $($SubscriptionId)"
Connect-AzAccount -Tenant $TenantId -Subscription $SubscriptionId -Environment $Environment -ErrorAction Stop | Out-Null
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment