Filter Microsoft 365 Users by Location Using Graph PowerShell

Managing users in a Microsoft 365 tenant requires efficient filtering based on various attributes, including user location. Microsoft Graph PowerShell provides a seamless way to query and manage users efficiently. In this article, we will explore how to retrieve users based on their usage location using the Get-MgUser cmdlet.

PowerShell Script to Filter Users by Location


# Connect to Microsoft Graph PowerShell
Connect-MgGraph -Scopes "User.Read.All"
                                
# Prompt the admin to enter the user location
$UserLocation = Read-Host "Enter the user location (e.g., US, UK, IN)"
                                
# Retrieve users based on the entered location
$Users = Get-MgUser -All -Filter "usageLocation eq '$UserLocation'" -Property Id, DisplayName, UsageLocation | Select-Object Id, DisplayName, UsageLocation
                                
# Check if any users were found
if ($Users.Count -eq 0) {
Write-Host "No users found with the specified location: $UserLocation" -ForegroundColor Yellow
} else {
# Display results
$Users | Format-Table -AutoSize
}
                            

How the Script Works

  1. Connects to Microsoft Graph:
    The script starts by establishing a connection to Microsoft Graph with the User.Read.All permission.
  2. Prompts for User Location:
    The admin is asked to enter the location (e.g., US, UK, IN).
  3. Filters Users by Location:
    The Get-MgUser cmdlet retrieves users whose usageLocation matches the entered value.
  4. Optimizes Output
    Only required properties (Id, DisplayName, UsageLocation) are retrieved for efficiency.
  5. Displays Results or a Warning
    If no users match the location, a message is displayed.

Further Enhancements

  • Allow Multiple Locations:
    The script can be modified to accept multiple locations, allowing admins to filter users in different regions simultaneously.
  • $Locations = @("US", "UK", "CA")
    $FilterQuery = ($Locations | ForEach-Object { "usageLocation eq '$_'" }) -join " or "
    $Users = Get-MgUser -All -Filter $FilterQuery -Property Id, DisplayName, UsageLocation
                                    
  • Export Results to CSV:
    To facilitate data reporting and sharing, export the retrieved user list to a CSV file.
  • $Users | Export-Csv -Path "UsersByLocation.csv" -NoTypeInformation
  • Perform Case-Insensitive Search:
    By default, -Filter requires an exact match, but a case-insensitive search can be performed using -Search.
  • Get-MgUser -All -Search "usageLocation:US" -Property Id, DisplayName, UsageLocation
  • Enhance Error Handling:
    Adding error handling ensures the script is more user-friendly and informative.
  • if ($Users.Count -eq 0) {
    Write-Host "No users found for '$UserLocation'. Please check the location code." -ForegroundColor Red
    }
                                    
  • Integration with License Management:
    The retrieved user list can be used to assign or remove licenses based on location.
  • $Users | ForEach-Object {
    Set-MgUserLicense -UserId $_.Id -AddLicenses @{SkuId = "ENTER_SKUID"} -RemoveLicenses @{}
    }
                                    

Use Cases

  1. License Management: Organizations often have different licensing requirements based on geography. This script helps IT teams filter users by location and apply necessary license assignments.
  2. Compliance Audits: Some countries have strict compliance regulations regarding user data and access. Filtering users by location allows admins to verify compliance with local laws.
  3. Targeted Communications: HR or IT teams may need to send location-specific announcements or surveys to users based in certain countries.
  4. Security Policy Enforcement: Certain security policies, such as Conditional Access policies, may need to be enforced based on the user's location. This script helps identify users affected by such policies.
  5. Departmental Segmentation: Filtering users by region can help segment employees for regional IT support or operational efficiency.
  6. User Migration Planning: Organizations undergoing mergers or transitions can use location-based filtering to facilitate smooth migration processes for regional offices.
  7. Identifying Inactive or Unauthorized Users: Admins can use this script to detect users with outdated or incorrect location details that may need to be updated in the directory.

Possible Errors and Solutions

Error Cause Solution
"Cannot convert the literal 'System.Collections.Hashtable' to the expected type 'Edm.Guid'" Incorrect format for the -AddLicenses parameter. Use the correct format: @(@{SkuId = "<SkuId>"}).
Insufficient Permissions The required Graph API permissions (User.ReadWrite.All, Directory.ReadWrite.All) are not granted. Ensure the app has appropriate permissions in Azure AD and admin consent is provided.
License Exhausted No available licenses in the tenant. Check license availability using Get-MgSubscribedSku and acquire additional licenses if needed.

Conclusion

Efficient license management is vital for cost optimization in Microsoft 365. By automating the reassignment of freed licenses to unlicensed users, this script ensures optimal use of your organization’s resources. Implementing such tools reduces manual overhead and enables administrators to focus on strategic tasks. Try the script today and streamline your license management process!

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