Managing users within Microsoft 365 can be challenging, especially when needing to filter and retrieve user data from specific departments. Microsoft Graph PowerShell simplifies this process, allowing administrators to fetch user details quickly and efficiently. This article presents a ready-to- use script to list all users belonging to a specified department, along with their essential details, using Microsoft Graph PowerShell.
# Install and import the Microsoft Graph module if not already installed
# Install-Module Microsoft.Graph -Scope CurrentUser
# Connect to Microsoft Graph
Connect-MgGraph -Scopes "User.Read.All"
# Specify the Department
$department = "Finance" # Change this to your target department
# Fetch users from the specified department
$users = Get-MgUser -All -Filter "department eq '$department'" -Property UserPrincipalName, Mail,
Department, AssignedLicenses
# Display user details
$users | Select-Object `
@{Name="UserPrincipalName"; Expression={$_.UserPrincipalName}}, `
@{Name="Email"; Expression={$_.Mail}}, `
@{Name="Department"; Expression={$_.Department}}, `
@{Name="Licensed"; Expression={if ($_.AssignedLicenses.Count -gt 0) {"Yes"} else {"No"}}} |
Format-Table -AutoSize
Error | Cause | Solution |
---|---|---|
Access Denied | Insufficient permissions | Ensure User.Read.All permission is granted.. |
Invalid Filter Clause | Incorrect or unsupported filter format | Check the filter string and correct syntax. |
No Users Found | Department name is incorrect or no users exist | Verify the department name provided. |
Could not connect to Microsoft Graph | Network issues or incorrect credentials | Check your internet connection and credentials. |
This script provides a quick and efficient way to fetch user details from a specific department in Microsoft 365 using Microsoft Graph PowerShell. By dynamically filtering users and presenting essential details, it aids administrators in managing and auditing departmental user data. Further enhancements like CSV export, dynamic inputs, and error handling can make it even more versatile and user-friendly.
© M365Corner. All Rights Reserved.