Azure Subscription Chooser PowerShell Script

If you want to execute a PowerShell scripts that does something in Azure, you might want to start your script with making sure the right subscription is chosen.


I had a task to automate creation of Azure resources required for an application that we were building. I used a combination of ARM Templates and Azure PowerShell to create the resources, but I had to make sure that whoever would run the script had an option of choosing whichever subscription they wanted. This way it was easy to package up the application, and just have single script that will set up required cloud resources.

If you are just starting with Azure, you probably have only one tenant and only one Pay-As-You-Go subscription. But if you are a regular Azure user, you might have your MSDN subscription, your company’s subscription, plus any other subscriptions attached to one or more of your customers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
$azExists = Get-InstalledModule Az -AllVersions -ErrorAction SilentlyContinue

if ($azExists) {
Write-Host "Az PowerShell installed ..."
}
else {
Write-Host "You need Az PowerShell https://docs.microsoft.com/en-us/powershell/azure/"
Break
}

Import-Module Az

# https://github.com/Azure/azure-powershell/issues/8628#issuecomment-478644165
$azureContext = Disable-AzContextAutosave -Scope Process
Clear-AzContext
# Clear-AzContext -Scope CurrentUser -Force # https://github.com/Azure/azure-powershell/issues/8628

$azureAccount = Connect-AzAccount

$azureSubscriptions = Get-AzSubscription

$azureSubscriptionCounter = 1
foreach ($azureSubscription in $azureSubscriptions) {
Write-Output "($azureSubscriptionCounter) $($azureSubscription.Name)"
$azureSubscriptionCounter++;
}

$subscriptionNumber = Read-Host 'Please choose subscription'

$subscription = Select-AzSubscription -SubscriptionId $azureSubscriptions[$subscriptionNumber - 1].Id

While creating this script I found an interesting behavior in the Connect-AzAccount step. You might not be offered subscriptions from the account you signed in with. This script fixes that, and details are linked in commented out code.