Private/Invoke-365TuneElevation.ps1

function Invoke-365TuneElevation {
    <#
    .SYNOPSIS
        Elevates current user to User Access Administrator at root scope.
    #>


    $elevateUri = "https://management.azure.com/providers/Microsoft.Authorization/elevateAccess?api-version=2015-07-01"

    # Get ARM token; fall back to az CLI if Get-AzAccessToken fails (e.g. CLI bridge context)
    try {
        $armObj = Get-AzAccessToken -ResourceUrl "https://management.azure.com" -ErrorAction Stop
        $armStr = if ($armObj.Token -is [System.Security.SecureString]) { [System.Net.NetworkCredential]::new("", $armObj.Token).Password } else { $armObj.Token }
    } catch {
        $armStr = az account get-access-token --resource https://management.azure.com --query accessToken -o tsv 2>$null
        if (-not $armStr) { throw "Could not obtain ARM access token for elevation." }
    }

    $headers    = @{ Authorization = "Bearer $armStr"; "Content-Type" = "application/json" }
    $statusCode = $null
    try {
        $resp       = Invoke-WebRequest -Uri $elevateUri -Method POST -Headers $headers -UseBasicParsing
        $statusCode = [int]$resp.StatusCode
    } catch {
        if ($_.Exception.Response) {
            $statusCode = [int]$_.Exception.Response.StatusCode
        } else {
            throw
        }
    }

    if ($statusCode -notin @(200, 204)) {
        throw "Elevation failed with status: $statusCode. Ensure 'Access management for Azure resources' is enabled in Entra ID > Properties."
    }

    # Brief pause to allow elevation to propagate
    Start-Sleep -Seconds 3

    Write-Host " [OK] Elevated to User Access Administrator." -ForegroundColor Green
}