Quickly Switch Azure Subscriptions with PSNotes

If you are now aware, PSNotes is a PowerShell module I developed that allows you save code snippets, and recall them right in you PowerShell using an alias. One great use for this I have found is for switching between Azure subscriptions. 

I work in multiple different subscriptions throughout the day. Some are in the same tenant, but some require me to authenticate with different accounts. So, I wrote the code block below that attempts to switch subscriptions, but if it can’t with the current logged in user, it prompts me to authenticate.

$SubscriptionId = ''
if($(Get-AzContext).Subscription.SubscriptionId -ne $SubscriptionId){
    Set-AzContext -SubscriptionId $SubscriptionId -ErrorAction SilentlyContinue
    if($(Get-AzContext).Subscription.SubscriptionId -ne $SubscriptionId){
        Clear-AzContext -Scope CurrentUser -Force -ErrorAction SilentlyContinue
        Clear-AzDefault -Force -ErrorAction SilentlyContinue
        $connect = Add-AzAccount -SubscriptionId $SubscriptionId
    }
}

This works great, but I still need to remember the GUID of every subscription I need to connect to. This is where the PSNotes module comes in handy. Using the New-PSNote command, I can create an alias for every subscription I regularly connect to. For example, I used the command below to create an alias for my development subscription.

New-PSNote -Note 'AzDev' -Tags 'AzConnect' -Alias 'AzDev' -ScriptBlock{
	$SubscriptionId = 'ca21f08b-8a8e-4997-9e6e-515aa470c0a2'
	if($(Get-AzContext).Subscription.SubscriptionId -ne $SubscriptionId){
		Set-AzContext -SubscriptionId $SubscriptionId -ErrorAction SilentlyContinue
		if($(Get-AzContext).Subscription.SubscriptionId -ne $SubscriptionId){
			Clear-AzContext -Scope CurrentUser -Force -ErrorAction SilentlyContinue
			Clear-AzDefault -Force -ErrorAction SilentlyContinue
			$connect = Add-AzAccount -SubscriptionId $SubscriptionId
		}
	}
	Write-Host "You are now connected to $($(Get-AzContext).Subscription.Name)"
}

Now all I need to do to connect to this subscription is type “AzDev -run” into my console, and I’m connected to my development subscription.

One response to “Quickly Switch Azure Subscriptions with PSNotes”