This PowerShell script is designed for administrators who need to manage and analyze the geographic distribution of Microsoft 365 users within their organization. By connecting to Microsoft Graph, the script fetches and displays the number of users in each city, state, and country, providing valuable insights into where users are located.
This information can be crucial for compliance with regional data protection regulations, optimizing service delivery, and planning network infrastructure upgrades. The script enhances administrative capabilities by simplifying the process of gathering and organizing user location data efficiently.
Run the below command to install Microsoft Graph PowerShell module.
Connect to Microsoft Graph using User.Read.All permission that is required to read all the user profiles in your organization.
Get-MgUser fetches user information. The -All parameter ensures all users are fetched (useful when pagination might occur). The -Property parameter helps you to select and display id, displayName, city, state, and country user properties.
Group-Object groups the collection of user objects by the specified property (country, state, city). Select-Object then formats the output to show the Name of the group (the geographic location) and the Count of users in that location.
Write-Output is used to print a heading for each section. Format-Table -AutoSize formats the output into a readable table where column widths automatically adjust to content size. $groupedByCountry, $groupedByState and $groupedByCity contain the country/state/city-wise user locations along with the total user counts.
Here's the entire script for your reference:
Connect-MgGraph -Scopes "User.Read.All"
# Get the geographical location information of all users
$users = Get-MgUser -All -Property id, displayName, city, state, country
# Group and count users by city, state, and country
$groupedByCountry = $users | Group-Object -Property country | Select-Object Name, Count
$groupedByState = $users | Group-Object -Property state | Select-Object Name, Count
$groupedByCity = $users | Group-Object -Property city | Select-Object Name, Count
# Output the count of users in each country
Write-Output "Count of users by country:"
$groupedByCountry | Format-Table -AutoSize
# Output the count of users in each state
Write-Output "Count of users by state:"
$groupedByState | Format-Table -AutoSize
# Output the count of users in each city
Write-Output "Count of users by city:"
$groupedByCity | Format-Table -AutoSize
# Disconnect the session
Disconnect-MgGraph
© m365corner.com. All Rights Reserved. Design by HTML Codex