Fetching Microsoft 365 Global Administrator Info Using Graph PowerShell

In this article, we'll walk you through a PowerShell script that counts the number of Global Administrators in a Microsoft 365 tenant and lists their personal details. This script utilizes the Microsoft Graph PowerShell module, which provides a powerful way to interact with the Microsoft Graph API.


Script Overview

Here is the complete script that performs the task:

# Ensure the Microsoft.Graph module is installed and imported
if (-not (Get-Module -ListAvailable -Name Microsoft.Graph)) {
    Install-Module -Name Microsoft.Graph -Scope CurrentUser -Force -AllowClobber
}

Import-Module Microsoft.Graph

# Connect to Microsoft Graph with necessary Graph API Permissions
Connect-MgGraph -Scopes "User.Read.All", "RoleManagement.Read.Directory"

# Get all directory roles
$roles = Get-MgDirectoryRole

# Find the role ID for global administrators
$globalAdminRole = $roles | Where-Object { $_.DisplayName -eq "Global Administrator" }

# Initialize counts and arrays for storing details
$totalGlobalAdmins = 0
$globalAdminDetails = @()

# Get the members of the global administrator role
if ($globalAdminRole -ne $null) {
    $globalAdmins = Get-MgDirectoryRoleMember -DirectoryRoleId $globalAdminRole.Id -All
    $totalGlobalAdmins = $globalAdmins.Count
    $globalAdmins | ForEach-Object {
        $user = Get-MgUser -UserId $_.Id
        $globalAdminDetails += [PSCustomObject]@{
            DisplayName = $user.DisplayName
            Email = $user.UserPrincipalName
        }
    }
}

Write-Output "Total Global Administrators: $totalGlobalAdmins"
Write-Output "Global Administrators Details:"
$globalAdminDetails | Format-Table -AutoSize

Note: Replace "Global Administrator" with the display name of the administrator whose details you want to fetch (example: "Exchange Administrator") in the script to suit your requirements.

Script Output


Script Explanation

  1. Importing Microsoft Graph Module: The script first checks if the Microsoft.Graph module is installed. If not, it installs the module. The module is then imported to use its cmdlets.
  2. Connecting to Microsoft Graph: The Connect-MgGraph cmdlet is used to connect to Microsoft Graph with the required permissions (User.Read.All and RoleManagement.Read.Directory).
  3. Fetching Directory Roles: All directory roles are retrieved using Get-MgDirectoryRole.
  4. Identifying Global Administrators: The script filters the roles to find the Global Administrator role.
  5. Counting and Listing Global Administrators: The members of the Global Administrator role are fetched using Get-MgDirectoryRoleMember. For each member, their display name and email (UserPrincipalName) are retrieved (using Get-MgUser) and stored.
  6. Output: The total count of Global Administrators is displayed. Details of each Global Administrator are formatted and output in a table.

How to Improve the Script

  • Error Handling: Add try-catch blocks to handle any errors during the API calls, which ensures the script doesn't stop unexpectedly.
  • Logging: Implement logging to capture detailed information about the execution process for troubleshooting.
  • Optimization: Use parallel processing for fetching user details to speed up the execution, especially in larger environments.
  • Exporting Results: Export the details to a CSV file for easier analysis and record-keeping.

Frequently Asked Questions

  • Can I retrieve all administrator roles with a single command?
  • No, Get-MgDirectoryRoleMember requires you to pass a specific RoleId to retrieve members of that role. To enumerate all roles and their members, you first need to query available roles with Get-MgDirectoryRole.

  • How do I distinguish between permanent and eligible Global Administrators?
  • Permanent admins are always active in the role, while eligible admins (via Privileged Identity Management) may require activation. This distinction doesn’t appear directly in Graph PowerShell output; for eligibility details, you’ll need to use the Privileged Access Management endpoints.

  • What happens if a Global Administrator account is disabled?
  • The account will still show up as part of the Global Administrator role, but its accountEnabled property will be set to false. Including this property in your query helps identify and review inactive or blocked administrator accounts.

  • Is there a way to check the last sign-in of Global Administrators?
  • Yes. You can expand your query to include the signInActivity property of each user. This is particularly useful for spotting dormant admin accounts that may pose security risks.


Possible Errors and Solutions

Error Cause Solution
Module Installation Issues Issues with installing the Microsoft.Graph module. Ensure PowerShell is running with administrative privileges to install the module. Use -Scope CurrentUser to avoid permission issues.
Authentication Failures Problems connecting to Microsoft Graph. Check that the user has the necessary permissions to read directory roles and users. Verify the correct scopes are specified in Connect-MgGraph.
Network Issues Connectivity problems affecting interaction with Microsoft Graph API. Ensure there is a stable internet connection as the script interacts with the Microsoft Graph API.
Missing Roles or Members The specified roles or members do not exist in the tenant. Ensure that the roles and members exist and are correctly assigned in the tenant.

⚡ Use Parallelization for Fetching User Details

For tenants with many Global Administrators or when fetching large numbers of users, the ForEach-Object loop can become a bottleneck. Consider using PowerShell’s ForEach-Object -Parallel (available in PowerShell 7+) or background jobs to fetch user details concurrently, reducing runtime significantly.
🔍 Include Additional Properties for Security Insights

Listing just DisplayName and UserPrincipalName is useful, but you can gain better insight by including properties like AccountEnabled to identify disabled admins and signInActivity.lastSignInDateTime to spot inactive Global Administrator accounts. These checks help ensure privileged access is both active and appropriate.

Conclusion

This script provides a straightforward way to count and list Global Administrators in a Microsoft 365 tenant using the Microsoft Graph PowerShell module. By enhancing the script with error handling, logging, and optimization, you can ensure it runs smoothly and efficiently in various environments. This approach not only improves administrative oversight but also aids in maintaining security by keeping track of privileged accounts.

By leveraging Microsoft Graph PowerShell, administrators can automate and streamline their management tasks, making their operations more efficient and reliable.



Related Articles:

Using Get-MgDirectoryRole in Graph PowerShell
Using Get-MgUserLicenseDetail in Graph PowerShell
Using Find-GraphMgCommand in Graph PowerShell
Connect to Microsoft 365 Using PowerShell
How to Create Bulk Users in Office 365 Using Graph PowerShell?
Create Microsoft 365 Group Using Microsoft Graph PowerShell
Block Microsoft 365 User Using Microsoft Graph PowerShell
Assign Microsoft 365 License Using Graph PowerShell
Microsoft 365 User Management Using Graph PowerShell
Checking Group Membership in Microsoft 365
Bulk Assign Microsoft 365 License
Find Inactive Users in Microsoft 365
Using Powershell Graph Search Query
Using Powershell Graph Filter Query
Using Where-Object In Graph PowerShell
Using Expand Property In Graph PowerShell
Using Select Object In Graph PowerShell
Using -Contains Operator In Graph PowerShell
Add User to Multiple Microsoft 365 Groups Using Graph PowerShell
Get Microsoft 365 User Location Using Graph PowerShell
Import Microsoft 365 Groups from CSV File Using Graph PowerShell
Microsoft 365 Group User Import Using Graph PowerShell

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