๐Ÿ”ง New: User Management Graph PowerShell Toolkit

Simplify user tasks like bulk creation, updates, password resets, deletions, license checks & more โ€” all from one place.

๐Ÿš€ Launch Toolkit

Fetch Global Administrators and Email List with Graph PowerShell

Global Administrators hold the highest level of privileges in Microsoft 365. Keeping track of who holds this role is vital for security, compliance, and operational governance.

This simple script retrieves all Global Admins in your tenant and sends the list as a CSV attachment to a designated administrator via Microsoft Graph PowerShell.


i) Script

# ===== Simple Graph PowerShell Script =====
# Fetch all GLOBAL ADMINS and email the list to admin
# Requires: Microsoft.Graph module
# Scopes: Directory.Read.All, User.Read.All, Mail.Send
                                
# --- Variables ---
$FromUser  = "admin@contoso.com"      # Sender (must have mailbox)
$To        = "it-ops@contoso.com"     # Recipient
$Subject   = "Global Administrators report"
$CsvOutDir = "$env:TEMP"

# --- Connect to Microsoft Graph ---
Import-Module Microsoft.Graph -ErrorAction Stop
Connect-MgGraph -Scopes "Directory.Read.All","User.Read.All","Mail.Send"

# --- Resolve the 'Global Administrator' role object (handles legacy name too) ---
$globalRole = Get-MgDirectoryRole -Filter "displayName eq 'Global Administrator'"
if (-not $globalRole) {
    $globalRole = Get-MgDirectoryRole -Filter "displayName eq 'Company Administrator'"
}
if (-not $globalRole) {
    throw "Couldn't find the 'Global Administrator' (Company Administrator) role in this tenant."
}

# --- Get role members (directory objects) ---
$members = Get-MgDirectoryRoleMember -DirectoryRoleId $globalRole.Id -All

# --- Resolve only users (skip groups/service principals/devices) ---
$admins = foreach ($m in $members) {
try {
    Get-MgUser -UserId $m.Id -Property Id,DisplayName,UserPrincipalName,JobTitle,Department,AccountEnabled -ErrorAction Stop
} catch {
    # Not a user or not accessible; skip
}
}

# --- Export to CSV ---
if (-not (Test-Path -Path $CsvOutDir)) { New-Item -ItemType Directory -Path $CsvOutDir | Out-Null }
$ts = Get-Date -Format "yyyyMMdd_HHmmss"
$csvPath = Join-Path $CsvOutDir ("GlobalAdmins_{0}.csv" -f $ts)
$admins | Select-Object DisplayName,UserPrincipalName,JobTitle,Department,AccountEnabled,Id |
Export-Csv -Path $csvPath -NoTypeInformation -Encoding UTF8

# --- Prepare HTML Body ---
$summaryHtml = @"
<html>
  <body style='font-family:Segoe UI,Arial,sans-serif'>
    <h3>Global Administrators Report</h3>
    <p>Total global admins: <b>$($admins.Count)</b></p>
    <p>The full list is attached as a CSV.</p>
  </body>
</html>
"@
                                
# --- Prepare Attachment ---
$fileBytes     = [System.IO.File]::ReadAllBytes($csvPath)
$base64Content = [System.Convert]::ToBase64String($fileBytes)
$csvFileName   = [System.IO.Path]::GetFileName($csvPath)
$attachment = @{
"@odata.type" = "#microsoft.graph.fileAttachment"
    name          = $csvFileName
    contentBytes  = $base64Content
    contentType   = "text/csv"
}

# --- Prepare Mail Object ---
$mail = @{
    message = @{
    subject = "${Subject}"
    body    = @{
        contentType = "HTML"
        content     = $summaryHtml
    }
    toRecipients = @(@{ emailAddress = @{ address = $To } })
    attachments  = @($attachment)
    }
    saveToSentItems = $true
}

# --- Send Email ---
Send-MgUserMail -UserId $FromUser -BodyParameter $mail
                            

Write-Host "Done. CSV saved at: $csvPath" -ForegroundColor Green


ii) How the Script Works

  1. Variable Setup
  2. You define the sender and recipient email addresses, email subject, and CSV export location.

  3. Connecting to Microsoft Graph
  4. The script loads the Microsoft Graph PowerShell module and signs in with delegated permissions:

    • Directory.Read.All โ€” to read directory role information.
    • User.Read.All โ€” to fetch user details.
    • Mail.Send โ€” to send emails.
  5. Resolving the Global Administrator Role
  6. The script checks for directory objects designated with role Global Administrator.

  7. Fetching Role Members
  8. Get-MgDirectoryRoleMember retrieves all members of the Global Admin role. These can include users, groups, service principals, or devices.

  9. Filtering for Users Only
  10. The loop tries Get-MgUser for each ID. If itโ€™s a user, details like DisplayName, UPN, JobTitle, Department, and AccountEnabled status are returned; non-user IDs are skipped.

  11. Exporting to CSV
  12. The user list is saved to a timestamped CSV file.

  13. Email Preparation and Sending
  14. The script creates a simple HTML summary, attaches the CSV, and sends it from $FromUser to $To using Send-MgUserMail.


iii) Further Enhancements

  • CSV Preview in Email: Embed the first 10 records directly in the HTML body for quick reference.
  • Multiple Roles: Extend the script to fetch other privileged roles like Privileged Role Administrator or SharePoint Administrator.
  • Scheduled Reports: Use Task Scheduler or Azure Automation to run the script periodically.
  • Audit Logging: Save a copy of the CSV to a SharePoint library or Azure storage for compliance.
  • Batch Processing: Optimize API calls by batching user lookups if you have a large number of admins.

iv) Use Cases

  • Security Audits: Regularly review who has global admin rights to detect privilege creep.
  • Incident Response: Quickly pull and share a list of high-privilege accounts in case of a breach.
  • Compliance Checks: Generate and archive reports for governance and certification processes.
  • Operational Oversight: Send periodic summaries to senior IT leadership or security teams.

v) Possible Errors & Solutions

Error Cause Solution
Authorization_RequestDenied Missing required Graph scopes or consent not granted Reconnect with Directory.Read.All, User.Read.All, and Mail.Send scopes; ensure admin consent.
Couldn't find the 'Global Administrator' Role name mismatch or role not activated in the tenant Check with Get-MgDirectoryRole to confirm active roles; enable via Azure AD portal if needed.
Get-MgUser not recognized Users module not installed Install unified Microsoft.Graph or Microsoft.Graph.Users module.
Empty CSV output No active global admins or IDs resolved as groups/devices Verify in Entra admin center and adjust role membership if necessary.
Email not sent $FromUser account lacks a mailbox or send rights Use a mailbox-enabled account with permissions to send to $To.

vi) Conclusion

This script gives you a straightforward way to identify all Global Administrators in your Microsoft 365 tenant and deliver that list directly to an adminโ€™s inbox. With minimal modification, it can become part of a regular security and compliance reporting process, ensuring your privileged access is always under control.


Graph PowerShell Explorer Widget

20 Graph PowerShell cmdlets with easily accessible "working" examples.


Permission Required

Example:


                


                


                

© m365corner.com. All Rights Reserved. Design by HTML Codex