functions/azure/Test-AzContextAndConnect.ps1

function Test-AzContextAndConnect {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [guid]$TenantId,
        [Parameter(Mandatory = $false)]
        [guid]$SubscriptionId = [guid]::Empty,
        [Parameter(Mandatory = $true)]
        [string]$ServicePrincipalName,
        [Parameter(Mandatory = $true)]
        [string]$Endpoint
    )

    $storedCredentials = Get-AzStoredServicePrincipalCredential `
        -TenantId $TenantId `
        -SubscriptionId $SubscriptionId `
        -ServicePrincipalName $ServicePrincipalName

    $clientId = $storedCredentials.Credential.UserName
    $scope = Get-ScopeFromEndpoint -Endpoint $Endpoint

    $needsReconnect = $BcAdminSession.AzureTenantId -ne $TenantId -or
        $BcAdminSession.AzureSubscriptionId -ne $SubscriptionId -or
        $BcAdminSession.AzureClientId -ne $clientId -or
        $null -eq $BcAdminSession.AzureAccessTokens[$scope]

    if ($null -ne $BcAdminSession.AzureAccessTokens[$scope]) {
        $needsReconnect = $BcAdminSession.AzureAccessTokens[$scope].valid_to -le (Get-Date).AddSeconds(-60)
        if ($needsReconnect) {
            Write-Warning "API access_token will be invalid in less than 60 seconds! Reconnecting."
        }
    }

    if ($needsReconnect) {
        return (Connect-ToAzure -TenantId $TenantId -SubscriptionId $SubscriptionId -ClientId $clientId -ClientSecret $storedCredentials.Credential.Password -Endpoint $Endpoint)
    } else {
        return $true
    }
}