Fetching Users with Assigned Managers using Graph PowerShell

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.

PowerShell Script to Fetch Users with Assigned Managers

# 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

How the Script Works

  • Connect to Microsoft Graph API: The script starts by authenticating to Microsoft Graph with the required scopes.
  • Fetches All Users: Get-MgUser retrieves all users in the tenant along with their Id and UserPrincipalName.
  • Retrieves Assigned Managers: For each user, Get-MgUserManager is used to fetch the Manager’s ID.
  • Fetches Manager Details: Since Get-MgUserManager only returns the ID, a second call to Get-MgUser retrieves the Manager’s UPN.
  • Stores and Displays the Data: The results are stored in an array and displayed in a formatted table in the console.

Further Enhancements

While the current script efficiently fetches users with assigned managers, here are some possible enhancements:

  • Export to CSV for Reporting: If you need to store or analyze the data further, exporting the results to a CSV file can be useful.
  • $usersWithManagers | Export-Csv -Path "C:\Users\ManagersReport.csv" -NoTypeInformation -Encoding UTF8
  • Filter by Department or Job Title: If you want to fetch users from specific departments or job roles, you can apply a filter before retrieving manager details.
    $filteredUsers = Get-MgUser -All -Filter "department eq 'Sales'" -Property Id, UserPrincipalName
  • Email Reporting to HR or IT: Automate report delivery by emailing it directly using Send-MgUserMessage.
  • Bulk Update Manager Assignments: Extend the script to assign managers in bulk using Set-MgUserManager.
    $EmailsToArchive | Select-Object Subject, ReceivedDateTime | Export-Csv -Path "ArchivedEmailsLog.csv" -NoTypeInformation
  • Send Notifications: Email the summary of archived emails to administrators or users:
    Set-MgUserManager -UserId user@contoso.com -ManagerId manager@contoso.com
  • Integration with Other M365 Reports: Combine this with license reports, security audits, or access logs for comprehensive management.

Use Cases

  • HR & IT Administration: Organizations can audit employee-manager relationships to ensure reporting structures are correctly configured in Microsoft 365.
  • Security & Compliance Many security policies and approval workflows depend on managers. This script helps verify that users have the correct assigned managers.
  • Automation & Auditing: This script can be automated to run periodically and send reports to HR or IT, ensuring that any manager changes are tracked and updated.
  • Performance Reviews & Workflows: Businesses often set up performance review workflows and approval chains based on managers. This script can be used to validate and update those workflows.
  • Custom Dashboards & Reporting: The script can be extended into Power BI or other reporting tools for a visual representation of user-manager relationships.

Possible Errors and Solutions

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

Conclusion

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