Access Azure subscription using context

Recently I was a little bit annoyed by logging each time to Azure subscription, so I’ve preperaed the script to Access Azure subscription using context.

What is context?

Azure Context are metadata used to authenticate Azure Resource Manager requests.
For more details please visit Microsoft docs site.

How script works?

Function which I prepared is used to save all contexts of Azure subscriptions assgined to account.
As the input parameter function require folder in which contexts will be stored.
If the provided folder path does not exist, function will create it if user agreed for that.
Once the folder is created function is checking if user is already logged in to Azure, if not script will ask to provide proper credentials.
Next it will list all subscriptions assigned to account and base on that create context files.

function Save-AzureContext {

        [Parameter(Position = 0, Mandatory = $true, HelpMessage = "Context folder", ValueFromPipeline = $false)] 
    if (!(Test-Path -Path $ContextFolder)) {

        $CreateFolder = Read-Host "Directory $ContextFolder does not exist. Do you want to create such folder? (Y/N)"
        if ($CreateFolder -eq "Y") {
            New-Item -Path $ContextFolder -ItemType Directory
        else {
            Write-Error "Path $ContextFolder does not exist and will not be created"

    If (!(Get-AzureRmContext)) {
        Write-Host "Please login to your Azure account"
    $Subscriptions = Get-AzureRmSubscription

    foreach ($sub in $Subscriptions) {
        Select-AzureRmSubscription -SubscriptionId $sub.Id
        $SubscriptionName = $sub.Name
        $ContextName = $SubscriptionName.Replace(" ", "")
        Save-AzureRmContext -Path $ContextFolder\$ContextName.json
        Write-Host "Context for subscription $SubscriptionName has been saved to $ContextFolder" -ForegroundColor Green

Once all subscriptions have context files, you can easly use them to login to Azure without providing any credentials.
Example of importing access Azure subscription using context code below.

Import-AzureRmContext -Path D:\Context\SubscriptionNameWIthoutSpaces.json

I hope it will be usefull for some of you 😉

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.