Introduction
If you are like me and have to work with many Azure subscriptions with Azure CLI
, you must have reached the point where you got tired of inner dialogs and commands like the following...
Which subscription am I right now?
az account show -o table
Okay, but I want to switch to that DEV subscription... but what again was the subscription id?
az account list -o table
Then you start copying & pasting the Id into...
az account set -n <id>
That is... wasteful ⏰ So here is a short timesaver I use in my PowerShell $profile
to speed up things.
My Setup
- Edit your PowerShell Profile, e.g., with Visual Studio Code
code $profile
- Paste this function to the end of your profile and save
Function Switch-AzContext {
if (-not (Get-Command az -ErrorAction SilentlyContinue)) {
Write-Host -ForegroundColor Red 'Azure CLI not installed!'
break
}
$azContext = az account list -o json | ConvertFrom-Json
$azActive = $azContext | Where-Object { $_.isDefault -eq $true}
$available = @()
$azContext | ForEach-Object { $index = 1 } {
if ($_.Id -eq $azActive.Id) {
$available += [PSCustomObject]@{
Active = "=>"
Index = $index++
Subscription = $_.Name
SubscriptionId = $_.Id
Account = $_.user.Name
}
}
else {
$available += [PSCustomObject]@{
Active = $null
Index = $index++
Subscription = $_.Name
SubscriptionId = $_.Id
Account = $_.user.Name
}
}
}
$available | Format-Table
try {
[int]$userInput = Read-Host "Index (0 to quit)"
if ($userInput -eq 0) {
Write-Host -ForegroundColor Red 'Wont switch Azure CLI context!'
break
} elseif ($userInput -lt 1 -or $userInput -gt $index-1) {
Write-Host -ForegroundColor Red 'Input out of range'
break
}
$selection = $available | Where-Object { $_.Index -eq $userInput }
Write-Host -ForegroundColor Cyan 'Switching to:', $selection.Subscription
az account set --subscription $selection.SubscriptionId
} catch {
Write-Host -ForegroundColor Red "Luke, wrong input, the index you must use!"
}
}
- You might want to add an alias on top just like I did
Set-Alias -Name azsw -Value Switch-AzContext
- Reread your profile by issuing
. $profile
Profit
Now can quickly switch between your Azure subscriptions by entering azsw
followed by the listed index. Sweet, isn't it! 😎