Export Manager of All Microsoft 365 Users using Graph API in PowerShell

We can use the Get-AzureADUser cmdlet from the Azure AD PowerShell module to get user details and use the Get-AzureADUserManager cmdlet to get the user’s manager info. We have already explained in another post to export manager of Office 365 users using the Azure AD PowerShell. In this post, we are going to explain how to export the manager of all Microsoft Office 365 users using Microsoft Graph API. 

We need an OAuth Access Token to connect Microsoft Graph API resources. Fetching user reports require the “User.Read.All” permission, either with Application or Delegated permission.

We can use the MSAL.PS library to acquire access tokens with Delegated permissions. Run the following command in PowerShell to install this module.

Install-Module -Name MSAL.PS

Run the following commands to get Access Token on behalf of a user.

#Provide your Office 365 Tenant Domain Name or Tenant Id
$TenantId = "contoso.onmicrosoft.com"
#$TenantId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
   
#Used the Microsoft Graph PowerShell app id. You can create and use your own Azure AD App id.
$AppClientId="14d82eec-204b-4c2f-b7e8-296a70dab67e"  
   
$MsalParams = @{
   ClientId = $AppClientId
   TenantId = $TenantId
   Scopes   = "https://graph.microsoft.com/User.Read.All"
}
  
$MsalResponse = Get-MsalToken @MsalParams
$AccessToken  = $MsalResponse.AccessToken

Once you get the required Access Token, we can use the Invoke-RestMethod cmdlet to call the Rest API with the token. The below script retrieves all Azure AD users with their manager info and exports the result to a CSV file.

#Provide your access token. 
#$AccessToken="eyJ0eXAiOiJ......" 
 
#Form request headers with the acquired $AccessToken
$headers = @{'Content-Type'="application\json";'Authorization'="Bearer $AccessToken"}
 
#This request get users list with manager details.
$ApiUrl = "https://graph.microsoft.com/beta/users?`$select=displayName,userPrincipalName,id&`$expand=manager(`$select=displayName,userPrincipalName)&`$top=999"
 
$Result = @()
While ($ApiUrl -ne $Null) #Perform pagination if next page link (odata.nextlink) returned.
{
$Response = Invoke-RestMethod -Method GET -Uri $ApiUrl -ContentType "application\json" -Headers $headers
if($Response.value)
{
$Users = $Response.value
ForEach($User in $Users)
{
$Result += New-Object PSObject -property $([ordered]@{ 
UserName = $User.displayName
UserPrincipalName = $User.userPrincipalName
UserId = $User.id
Manager = if($User.manager) { $User.manager.displayName } Else {$null}
ManagerUPN  = if($User.manager) { $User.manager.userPrincipalName } Else {$null}
})
} 
}
$ApiUrl=$Response.'@odata.nextlink'
}
#Export the Result to CSV file
$Result | Export-CSV "C:\Temp\M365UsersManagerInfo.CSV" -NoTypeInformation -Encoding UTF8
Advertisement