Public/TenantConnection/Connect-CustomerGraph.ps1

function Connect-CustomerGraph {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [string]$CustomerTenantId
    )
    # 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 to re-use existing connections
        $graphContext = Get-MgContext -ErrorAction SilentlyContinue
        if($graphContext.TenantId -eq $CustomerTenantId -and $Global:GraphToken -and $Global:GraphToken.expirationDateTime -gt (Get-Date)) {
            Write-Host "Re-using existing Graph connection..." -ForegroundColor DarkGray
            return
        }
        try {
            if($CustomerTenantId -eq $PartnerTenantId) {
                Write-Host "Connecting to partner tenant"
                $Global:GraphToken = New-CustomPartnerAccessToken -Scopes 'https://graph.microsoft.com/.default' -TenantId $CustomerTenantId -AsApp:$false
            } else {
                $Global:GraphToken = New-CustomPartnerAccessToken -Scopes 'https://graph.microsoft.com/.default' -TenantId $CustomerTenantId -AsApp:$true
            }
        }
        catch {
            throw "Failed to generate a token for MS Graph: $_"
        }
        try {
            Connect-MgGraph -AccessToken ($Global:GraphToken.access_token | ConvertTo-SecureString -AsPlainText -Force) -NoWelcome
        }
        catch {
            throw "Failed to connect to MS Graph: $_"
        }
    }
}