Private/Connect-ToGraph.ps1

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

    $requiredScopes = @(
        "DeviceManagementConfiguration.Read.All",
        "DeviceManagementManagedDevices.Read.All",
        "DeviceManagementManagedDevices.PrivilegedOperations.All",
        "DeviceManagementScripts.Read.All"
    )

    # Disconnect any existing session to avoid stale token issues
    try {
        $existingContext = Get-MgContext -ErrorAction SilentlyContinue
        if ($existingContext) {
            Write-Host "Disconnecting existing session..." -ForegroundColor Yellow
            Disconnect-MgGraph -ErrorAction SilentlyContinue | Out-Null
        }
    }
    catch {
        # Ignore disconnect errors
    }

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

    $connectParams = @{
        Scopes = $requiredScopes
        NoWelcome = $true
    }
    if ($ClientId) { $connectParams.ClientId = $ClientId }
    if ($TenantId) { $connectParams.TenantId = $TenantId }

    try {
        Connect-MgGraph @connectParams -ErrorAction Stop -WarningAction SilentlyContinue | Out-Null
        $context = Get-MgContext

        if (-not $context) {
            Write-Host "Failed to establish Graph connection." -ForegroundColor Red
            return $false
        }

        Write-Host "Connected as: $($context.Account)" -ForegroundColor Green

        # Validate that all required scopes were granted
        $grantedScopes = $context.Scopes
        $missingScopes = $requiredScopes | Where-Object { $_ -notin $grantedScopes }

        if ($missingScopes) {
            Write-Host "`nWARNING: Missing required permissions:" -ForegroundColor Yellow
            $missingScopes | ForEach-Object { Write-Host " - $_" -ForegroundColor Yellow }
            Write-Host "`nThe tool may not work correctly without these permissions." -ForegroundColor Yellow
            Write-Host "If using a custom app registration, ensure it has all required API permissions." -ForegroundColor Yellow
            Write-Host "See README.md for app registration setup instructions.`n" -ForegroundColor Yellow
        }

        return $true
    }
    catch {
        Write-Host "Authentication failed: $_" -ForegroundColor Red
        if ($_.Exception.Message -match "AADSTS\d+") {
            Write-Host "`nTip: If using a custom app, verify:" -ForegroundColor Yellow
            Write-Host " 1. ClientId and TenantId are correct" -ForegroundColor Yellow
            Write-Host " 2. App has all required API permissions" -ForegroundColor Yellow
            Write-Host " 3. Admin consent has been granted`n" -ForegroundColor Yellow
        }
        return $false
    }
}