Private/Connect-ToGraph.ps1

function Connect-ToGraph {
    param(
        [string]$ClientId,
        [string]$TenantId,

        # Request the extra permissions needed for Entra ID group targeting.
        # Only asked for when targeting a group, so other modes need no extra consent.
        [switch]$IncludeGroupScopes
    )

    Write-Host "Connecting to Microsoft Graph..." -ForegroundColor Green

    $connectParams = @{
        Scopes = @(
            "DeviceManagementConfiguration.Read.All",
            "DeviceManagementManagedDevices.Read.All",
            "DeviceManagementManagedDevices.PrivilegedOperations.All"
        )
        NoWelcome = $true
    }
    if ($IncludeGroupScopes) {
        # GroupMember.Read.All: look up groups and list their (nested) members
        # Device.Read.All: read each device member's deviceId, used to match it to Intune.
        # Without it Graph returns device members with only their id, so nothing matches.
        $connectParams.Scopes += @(
            "GroupMember.Read.All",
            "Device.Read.All"
        )
    }
    if ($ClientId) { $connectParams.ClientId = $ClientId }
    if ($TenantId) { $connectParams.TenantId = $TenantId }

    try {
        Connect-MgGraph @connectParams -ErrorAction Stop -WarningAction SilentlyContinue | Out-Null
        $context = Get-MgContext
        Write-Host "Connected as: $($context.Account)" -ForegroundColor Green
        return $true
    }
    catch {
        Write-Host "Auth failed: $_" -ForegroundColor Red
        return $false
    }
}