public/Set-SubscriptionContext.ps1

<#
 .Synopsis
 Ensures that a given subscription id is the currently selected context in Az.
 .Description
 Optimizes the way the context switcj is happening by only performing the costly operation if the
 current context differs from the one which is currently in the context.
 .Parameter SubscriptionId
 The unique ID of the Azure subscription where the SQL Azure Server is located.
 .Parameter TenantId
 The unique ID of the tenant where the subscription lives in for faster context switch.
 .Example
 Set-AzdSubscriptionContext -SubscriptionId 12345 -TenantId 56789
 Ensures that the context is on subscription with ID 12345 with tenant 56789
 .Example
 Set-AzdSubscriptionContext -SubscriptionId 12345
 Ensures that the context is on subscription with ID 12345 without defining the tenant ID.
#>

Function Set-SubscriptionContext {
    [CmdLetBinding()]
    param (
        [Parameter()] [string] $TenantId,
        [Parameter()] [string] $SubscriptionId,        
        [switch] $NoLogo
    )
    begin {
        if (!$NoLogo.IsPresent) {            
            Write-Logo $MyInvocation.InvocationName
        }
        New-FunctionStartup
        Write-HostDebug "Retrieving current context..."
        $current = Get-AzContext 
    }
    process {
        if (!$?) {
            throw "Could not retrieve current Azure context. Maybe perform Login-AzAccount first."        
        }        
        if ($SubscriptionId -and $current.Subscription.Id -eq $SubscriptionId) {
            Write-HostInfo "Reusing context."
            return
        }        
        if ($TenantId -and $SubscriptionId) {
            Set-AzContext -Tenant $TenantId -Subscription $SubscriptionId -ErrorAction SilentlyContinue 
        }
        elseif ($TenantId) {
            if ($current.Tenant.Id -eq $TenantId) {
                Write-HostInfo "Reusing context."
                return
            }
            Set-AzContext -Tenant $TenantId -ErrorAction SilentlyContinue 
        }
        elseif ($SubscriptionId) {
            Set-AzContext -Subscription $SubscriptionId -ErrorAction SilentlyContinue
        }                        
        if (!$?) {            
            throw "Could not set context."
        }
        Write-HostSuccess "Changed context."
    }
}