Private/Remove-365TuneElevation.ps1
|
function Remove-365TuneElevation { <# .SYNOPSIS Removes User Access Administrator elevation from root scope. #> $assignment = Get-AzRoleAssignment -RoleDefinitionId "18d7d88d-d35e-4fb5-a5c3-7773c20a72d9" ` -ErrorAction SilentlyContinue | Where-Object { $_.Scope -eq "/" } if (-not $assignment) { Write-Host " Elevation already removed." -ForegroundColor Gray return } $assignmentGuid = $assignment.RoleAssignmentId.Split("/")[-1] # Use Invoke-RestMethod with full URL — Invoke-AzRestMethod has a known bug # constructing paths at root scope "/" and returns 403 in Cloud Shell $armTokenObj = Get-AzAccessToken -ResourceUrl "https://management.azure.com" if ($armTokenObj.Token -is [System.Security.SecureString]) { $armToken = [System.Net.NetworkCredential]::new("", $armTokenObj.Token).Password } else { $armToken = $armTokenObj.Token } $response = Invoke-RestMethod ` -Uri "https://management.azure.com/providers/Microsoft.Authorization/roleAssignments/$($assignmentGuid)?api-version=2022-04-01" ` -Method DELETE ` -Headers @{ Authorization = "Bearer $armToken" } ` -ErrorAction SilentlyContinue # Confirm removal $stillExists = Get-AzRoleAssignment -RoleDefinitionId "18d7d88d-d35e-4fb5-a5c3-7773c20a72d9" ` -ErrorAction SilentlyContinue | Where-Object { $_.Scope -eq "/" } if (-not $stillExists) { Write-Host " ✅ Elevation removed." -ForegroundColor Green } else { Write-Host "" Write-Host " ⚠️ Could not auto-remove elevation." -ForegroundColor Yellow Write-Host " ACTION REQUIRED: Manually remove 'User Access Administrator' at root scope." -ForegroundColor Yellow Write-Host " Portal: https://portal.azure.com/#view/Microsoft_Azure_PIMCommon/ResourceMenuBlade/~/MyActions/resourceId//resourceType/tenant/provider/Microsoft.Authorization" -ForegroundColor Yellow Write-Host "" } } |