Public/TenantConnection/Connect-CustomerExchange.ps1

function Connect-CustomerExchange {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [string]$CustomerTenantId,
        [Parameter()]
        [bool]$Retry
    )
    # Get SAM tokens if not already available
    begin {
        if (!$SAMTokens) {
            $SAMTokens = Get-SAMTokens
        }  
    }
    
    # Generate a token for MS graph, and connect with it.
    process {
        try {
            $exchangeToken = New-CustomPartnerAccessToken -Scopes 'https://outlook.office365.com/.default' -CustomerTenantId $CustomerTenantId
        }
        catch {
            Write-Error "Failed to generate a token for Exchange Online: $_"
        }
        try {
            # Try to re-use existing connections
            $ConnectionInformation = Get-ConnectionInformation -ErrorAction SilentlyContinue
            if($ConnectionInformation.DelegatedOrganization -eq $CustomerTenantId){
                return
            }
            Disconnect-ExchangeOnline -Confirm:$false -ErrorAction SilentlyContinue
            Connect-ExchangeOnline -DelegatedOrganization $CustomerTenantId -AccessToken $exchangeToken -ShowBanner:$false
        }
        catch {
            if($Retry -eq $true) {
                Write-Error "Failed to connect to Exchange Online: $_"
                return
            }
            Write-Host "Failed to connect to Exchange Online - perhaps they have not consented to our application correctly? Trying.." -ForegroundColor Yellow
            Set-SAMConsent -CustomerTenantId $CustomerTenantId
            Connect-CustomerExchange -CustomerTenantId $CustomerTenantId -Retry:$true
        }
    }
}