Private/PartnerActions/New-CustomPartnerAccessToken.ps1

function New-CustomPartnerAccessToken() {
    param(
        [Parameter(Mandatory)]
        [String]
        $Scopes,
        [Parameter(Mandatory)]
        [String]
        $TenantId,
        [Parameter()]
        [bool]$Retry
    )
    begin {
        if (!$SAMTokens) {
            $SAMTokens = Get-SAMTokens
        }  
    }
    process {
        # Get an access token for the partner application, to the target tenant
        try {
            $Response = Invoke-WebRequest -Uri "https://login.microsoftonline.com/$($TenantId)/oauth2/v2.0/token" -ContentType 'application/x-www-form-urlencoded' -Method POST -Body @{
                client_id     = $SAMTokens.ApplicationId
                client_secret = $SAMTokens.ApplicationSecret
                grant_type    = "refresh_token"
                refresh_token = $SAMTokens.RefreshToken
                scope         = $Scopes
            }
            $AccessToken = Get-DecodedJWT -Token ($Response.Content | ConvertFrom-Json).access_token
        }
        catch {
            if ($_.ErrorDetails.Message -like "*The user or administrator has not consented*" -and !$Retry) {
                Write-Host "Failed to connect due to missing application consent." -ForegroundColor Yellow

                # Check that we have the appropriate GDAP relationship setup
                Connect-CustomerGraph -CustomerTenantId $PartnerTenantId
                $Relationship = Get-MgTenantRelationshipDelegatedAdminRelationship -Filter "customer/tenantId eq '$($TenantId)' and startswith(DisplayName, 'Jysk IT')" -Top 1

                if (!$Relationship) {
                    throw "Failed to find a GDAP relationship for customer with ID $($TenantId)"
                }

                $AccessAssignments = Get-MgTenantRelationshipDelegatedAdminRelationshipAccessAssignment -DelegatedAdminRelationshipId $Relationship.Id
                if (!$AccessAssignments) {
                    Write-host "Failed to find any access assignments for GDAP relationship with ID $($Relationship.Id)."
                    Write-Host "Creating the access assignments now." -ForegroundColor Yellow
                    New-GDAPAccessAssignments -RelationshipId $Relationship.Id
                }

                if ($Scopes -eq "https://outlook.office365.com/.default") {
                    Connect-CustomerGraph -CustomerTenantId $TenantId
                    $ExchangeServicePrincipal = Get-MgServicePrincipal -Filter "appId eq '00000002-0000-0ff1-ce00-000000000000'"
                    if (!$ExchangeServicePrincipal) {
                        throw "Failed to find Exchange Online service principal. The customer does not have Exchange Online - and therefore connection is impossible."
                    }
                    else {
                        Write-Host "Found Exchange Online service principal, so we can try to consent to it."
                    }
                }
                Write-Host "Trying to get consent, and then re-trying connection attempt." -ForegroundColor Yellow
                Set-SAMConsent -CustomerTenantId $TenantId
                New-CustomPartnerAccessToken -Scopes $Scopes -TenantId $TenantId -Retry:$true
            }
            else {
                throw "Failed to get access token: $_"
            }
        }
        return $AccessToken 
    }
}