Private/Invoke-Graph.ps1
|
function Invoke-Graph { param( [string]$Uri, [string]$Method = "GET", [object]$Body ) $params = @{ Method = $Method; Uri = $Uri } if ($Body) { $params.Body = $Body | ConvertTo-Json -Depth 10 } try { return Invoke-MgGraphRequest @params } catch { $statusCode = $null $errorMessage = $_.Exception.Message # Extract HTTP status code if available if ($errorMessage -match '(\d{3})\s+(Forbidden|Unauthorized)') { $statusCode = $Matches[1] } # Handle specific error cases if ($statusCode -eq "403") { Write-Host "`nPermission Error (403 Forbidden):" -ForegroundColor Red # Extract the required scope from error message if available if ($errorMessage -match 'Application must have one of the following scopes: ([^"]+)') { $requiredScopes = $Matches[1] Write-Host "Missing required permission(s): $requiredScopes" -ForegroundColor Yellow } else { Write-Host "The current account lacks required permissions for this operation." -ForegroundColor Yellow } Write-Host "`nPossible solutions:" -ForegroundColor Cyan Write-Host " 1. Use Configure-IROD to set up a custom app registration with all required permissions" -ForegroundColor Gray Write-Host " 2. Ensure your app registration has these delegated permissions:" -ForegroundColor Gray Write-Host " - DeviceManagementConfiguration.Read.All" -ForegroundColor Gray Write-Host " - DeviceManagementScripts.Read.All" -ForegroundColor Gray Write-Host " - DeviceManagementManagedDevices.Read.All" -ForegroundColor Gray Write-Host " - DeviceManagementManagedDevices.PrivilegedOperations.All" -ForegroundColor Gray Write-Host " 3. Grant admin consent for these permissions in Azure AD`n" -ForegroundColor Gray } elseif ($statusCode -eq "401") { Write-Host "`nAuthentication Error (401 Unauthorized):" -ForegroundColor Red Write-Host "Your session may have expired or lacks valid credentials." -ForegroundColor Yellow Write-Host "Try disconnecting and reconnecting to Microsoft Graph.`n" -ForegroundColor Yellow } else { Write-Host "`nGraph API Error:" -ForegroundColor Red Write-Host $errorMessage -ForegroundColor Yellow } # Re-throw the error to let calling function handle it throw } } |