Private/Test-GraphConnection.ps1
|
function Test-GraphConnection { <# .SYNOPSIS Validates that a Microsoft Graph connection exists with the required scopes. .DESCRIPTION Checks for an active Microsoft Graph session and verifies that the required permission scopes (User.Read.All, Directory.Read.All, Reports.Read.All) are present. Returns $true if the connection is valid, or throws a terminating error with remediation guidance. .OUTPUTS System.Boolean #> [CmdletBinding()] param() $requiredScopes = @( 'User.Read.All' 'Directory.Read.All' 'Reports.Read.All' ) # Check that the Microsoft.Graph module is available if (-not (Get-Module -Name Microsoft.Graph.Authentication -ListAvailable -ErrorAction SilentlyContinue)) { throw "Microsoft.Graph PowerShell SDK is not installed. Run: Install-Module Microsoft.Graph -Scope CurrentUser" } # Check for an active connection try { $context = Get-MgContext -ErrorAction Stop } catch { throw "No active Microsoft Graph connection. Run: Connect-MgGraph -Scopes 'User.Read.All','Directory.Read.All','Reports.Read.All'" } if (-not $context) { throw "No active Microsoft Graph connection. Run: Connect-MgGraph -Scopes 'User.Read.All','Directory.Read.All','Reports.Read.All'" } # Verify required scopes $currentScopes = $context.Scopes $missingScopes = @() foreach ($scope in $requiredScopes) { if ($currentScopes -notcontains $scope) { $missingScopes += $scope } } if ($missingScopes.Count -gt 0) { $scopeList = $missingScopes -join "','" throw "Missing required Graph scopes: $($missingScopes -join ', '). Run: Connect-MgGraph -Scopes '$scopeList'" } Write-Verbose "Graph connection verified. Account: $($context.Account) | Tenant: $($context.TenantId)" return $true } |