Private/Test-GraphConnection.ps1

function Test-GraphConnection {
    <#
    .SYNOPSIS
        Validates that a Microsoft Graph connection is active with required scopes.
    #>

    [CmdletBinding()]
    param()

    try {
        $context = Get-MgContext -ErrorAction Stop
    }
    catch {
        throw "Microsoft Graph is not connected. Run Connect-MgGraph first. Required scopes: User.Read.All, Directory.Read.All, AuditLog.Read.All, Application.Read.All, RoleManagement.Read.Directory"
    }

    if (-not $context) {
        throw "Microsoft Graph is not connected. Run Connect-MgGraph first."
    }

    $requiredScopes = @(
        'User.Read.All',
        'Directory.Read.All',
        'Application.Read.All'
    )

    $missingScopes = $requiredScopes | Where-Object { $_ -notin $context.Scopes }

    if ($missingScopes.Count -gt 0) {
        Write-Warning "Missing recommended scopes: $($missingScopes -join ', ')"
        Write-Warning "Some audit functions may return incomplete results."
        Write-Warning "Reconnect with: Connect-MgGraph -Scopes 'User.Read.All','Directory.Read.All','AuditLog.Read.All','Application.Read.All','RoleManagement.Read.Directory'"
    }

    Write-Verbose "Graph connection active as $($context.Account) in tenant $($context.TenantId)"
}