Mapping organizational hierarchies is crucial for maintaining efficient workflows in Microsoft 365. The Get-MgUserManager cmdlet retrieves the manager details for a user, but it only provides the manager's User ID by default. To get additional information, such as Display Name, User Principal Name (UPN), and Email, you can pass the manager's ID to the Get-MgUser cmdlet. This article provides a working example to simplify the process of mapping users to their managers.
# Retrieve all users in the 'Sales' department
$users = Get-MgUser -Filter "Department eq 'Sales'" -All
foreach ($user in $users) {
# Get the manager's User ID
$managerId = (Get-MgUserManager -UserId $user.Id).Id
# Get detailed information about the manager
$manager = Get-MgUser -UserId $managerId
# Output user and manager details as a custom object
[PSCustomObject]@{
UserId = $user.UserPrincipalName
ManagerId = $manager.Id
ManagerDisplayName = $manager.DisplayName
ManagerUPN = $manager.UserPrincipalName
ManagerMail = $manager.Mail
}
}
Script Output:
$users = Get-MgUser -Filter "Department eq 'Sales'" -All
$managerId = (Get-MgUserManager -UserId $user.Id).Id
$manager = Get-MgUser -UserId $managerId
Error | Cause | Solution |
---|---|---|
Insufficient privileges to complete the operation. | Missing permissions like User.Read.All or User.Read.All. | Grant the necessary permissions in Azure AD or use a Global Admin account. |
The specified object was not found in the directory. | A user does not have a manager assigned. | Add a check to skip users without managers
|
Invalid filter clause. | Incorrect syntax in the filter query. | Verify that the Department property exists and the query syntax is correct. |
Combining Get-MgUserManager and Get-MgUser provides a powerful way to map organizational hierarchies in Microsoft 365. By retrieving detailed manager information for users, you can create actionable reports, troubleshoot access issues, and maintain an accurate view of reporting structures. Start using this approach today to enhance your administrative workflows.
© m365corner.com. All Rights Reserved. Design by HTML Codex