In a Microsoft 365 environment, administrators often need to fetch users and their assigned managers to streamline reporting and manage user hierarchies efficiently. This article provides a Graph PowerShell script to retrieve all users in the tenant who have assigned managers and list their UserPrincipalName (UPN) alongside their Manager’s UPN.
# Connect to Microsoft Graph (Ensure you have necessary permissions)
Connect-MgGraph -Scopes "User.Read.All", "User.ReadWrite.All"
# Fetch all users from the tenant
$users = Get-MgUser -All -Property Id, UserPrincipalName
# Initialize an array to store results
$usersWithManagers = @()
# Loop through each user to fetch their assigned manager
foreach ($user in $users) {
try {
# Get the Manager ID
$managerId = (Get-MgUserManager -UserId $user.Id -ErrorAction Stop).Id
# Fetch Manager's UPN using Get-MgUser
if ($managerId) {
$manager = Get-MgUser -UserId $managerId -Property UserPrincipalName -ErrorAction Stop
$usersWithManagers += [PSCustomObject]@{
UserUPN = $user.UserPrincipalName
ManagerUPN = $manager.UserPrincipalName
}
}
} catch {
# If no manager is assigned or any error occurs, ignore and continue
}
}
# Display the results in console
$usersWithManagers | Format-Table -AutoSize
While the current script efficiently fetches users with assigned managers, here are some possible enhancements:
$usersWithManagers | Export-Csv -Path "C:\Users\ManagersReport.csv" -NoTypeInformation -Encoding UTF8
$filteredUsers = Get-MgUser -All -Filter "department eq 'Sales'" -Property Id, UserPrincipalName
$EmailsToArchive | Select-Object Subject, ReceivedDateTime | Export-Csv -Path "ArchivedEmailsLog.csv" -NoTypeInformation
Set-MgUserManager -UserId user@contoso.com -ManagerId manager@contoso.com
Error | Cause | Solution |
Get-MgUserManager : NotFound | User has no assigned manager | Ignore or log users without managers |
Access Denied | Insufficient permissions | Ensure User.Read.All and User.ReadWrite.All permissions are granted |
Cannot retrieve user properties | Incorrect property reference | Ensure correct property names are used in Get-MgUser |
This Graph PowerShell script provides an efficient way to fetch all users with assigned managers in a Microsoft 365 tenant. By leveraging Microsoft Graph API, administrators can automate user hierarchy management, streamline reports, and improve compliance. The script can be further enhanced for exporting reports, filtering users, and bulk updating manager assignments. Try it out and optimize your M365 user management today!
© m365corner.com. All Rights Reserved. Design by HTML Codex