Using Expand Property In Graph PowerShell

In Microsoft Graph API, and by extension the PowerShell module, entities or resources like users, groups, or messages have relationships with other entities. For example, a user might have manager details or a group could have members. These related resources can be expanded inline with the -Expand parameter.

Note: Without -Expand parameter, you will be required to make separate Graph API calls to fetch such nested resources.

Here are some practical examples of how to use the -Expand parameter in Microsoft Graph PowerShell module commands:


Get User Manager Details

Here's the Graph PowerShell script that fetches the manager details of a user with the help of -Expand property.

# Retrieve the user along with their manager's details 
#Use the user id of the user whose manager you wish to fetch 
$userWithManager = Get-MgUser -UserId "9ccc0d2b-ff1f-4d13-9dcf-a42749fd27ba" -Expand "manager"
                                
# Output the manager's details
if ($userWithManager.Manager -ne $null) {
        # Extracting properties from AdditionalProperties dictionary
        $managerName = $userWithManager.Manager.AdditionalProperties["displayName"]
        $managerEmail = $userWithManager.Manager.AdditionalProperties["mail"]
        $managerJobTitle = $userWithManager.Manager.AdditionalProperties["jobTitle"]
                                
        # Check each property for null value and display appropriate message if null or empty
        $managerName = if ([string]::IsNullOrWhiteSpace($managerName)) { "Not Available" } else { $managerName }
        $managerEmail = if ([string]::IsNullOrWhiteSpace($managerEmail)) { "Not Available" } else { $managerEmail }
        $managerJobTitle = if ([string]::IsNullOrWhiteSpace($managerJobTitle)) { "Not Available" } else { $managerJobTitle }
                                
        Write-Output "Manager's Details:"
        Write-Output "Name: $managerName"
        Write-Output "Email: $managerEmail"
        Write-Output "Job Title: $managerJobTitle"
    } else {
        Write-Output "This user does not have a manager assigned."
}

How the Script Works?

  1. Retrieving User and Manager Details:
    • Get-MgUser is a cmdlet from the Microsoft Graph PowerShell SDK, used here to retrieve user information.
    • -UserId "9ccc0d2b-ff1f-4d13-9dcf-a42749fd27ba" specifies the unique identifier for the user you want to retrieve information for.
    • -Expand "manager" is an important parameter here. The Expand parameter is used to include related entities in the result. In this case, it retrieves the user's manager information along with the user's details. Without using -Expand, the manager information would not be included by default and would require a separate request.
  2. Checking if Manager Exists:
    • This condition checks if the Manager property of the user is not null, meaning it checks if the user has a manager assigned.
  3. Extracting Manager's Details:
    • If the user has a manager, the script extracts the manager's displayName, mail, and jobTitle from the AdditionalProperties dictionary of the Manager object.
  4. Handling Null or Missing Properties:
    • Each extracted property is checked to see if it is null or empty. If it is, the script replaces the null or empty value with "Not Available":
  5. Displaying the Manager's Details:
    • If the user has a manager, the script outputs the manager’s name, email, and job title:
  6. Handling Users without a Manager:
    • If the user does not have a manager ($userWithManager.Manager is null), the script displays a message stating that the user does not have a manager assigned:

    This script efficiently retrieves and displays both the user and their manager's details using a single call to the Microsoft Graph API, thanks to the -Expand parameter. This parameter minimizes the need for additional API calls and simplifies data management by pulling related information in one go.


Script Output

PowerShell command retrieving user details with expanded manager information using -Expand parameter

Get Direct Reports to Manager

Here's the Graph PowerShell script that fetches the direct reports to a manager with the help of -Expand property

# Retrieve the user along with their direct reports
$userWithDirectReports = Get-MgUser -UserId "1b3ed1a5-438e-4ce9-9f63-f880991afd3a" -Expand "directReports"
                                
# Output the direct reports' details
if ($userWithDirectReports.DirectReports -ne $null) {
        Write-Output "Direct Reports:"
        foreach ($report in $userWithDirectReports.DirectReports) {
                # Extracting properties from AdditionalProperties dictionary
                $name = $report.AdditionalProperties["displayName"]
                $email = $report.AdditionalProperties["mail"]
                $jobTitle = $report.AdditionalProperties["jobTitle"]
                                
                # Check each property for null value and display appropriate message if null or empty
                $name = if ([string]::IsNullOrWhiteSpace($name)) { "Not Available" } else { $name }
                $email = if ([string]::IsNullOrWhiteSpace($email)) { "Not Available" } else { $email }
                $jobTitle = if ([string]::IsNullOrWhiteSpace($jobTitle)) { "Not Available" } else { $jobTitle }
                                
                Write-Output "Name: $name"
                Write-Output "Email: $email"
                Write-Output "Job Title: $jobTitle"
        }
} else {
     Write-Output "This user has no direct reports."
}

How the Script Works?

  1. Retrieve User and Direct Reports:
    • Get-MgUser is a cmdlet that fetches user information from Microsoft Graph.
    • -UserId "1b3ed1a5-438e-4ce9-9f63-f880991afd3a" specifies the unique identifier of the user you want to query.
    • -Expand "directReports" is crucial here. The Expand parameter tells the Microsoft Graph API to not only fetch the primary entity (the user) but also expand and include related entities—in this case, the user's direct reports. Without using -Expand, you would only receive the primary user's data, and additional requests would be needed to fetch each direct report.
  2. Check if Direct Reports Exist:
    • This checks if the DirectReports property is populated, indicating that the user has direct reports.
  3. Loop Through Each Direct Report
    • Iterates over each direct report retrieved. For each direct report, it extracts and potentially modifies the display of certain properties like name, email, and job title.
  4. Extract and Display Properties:
    • Each property (name, email, job title) is extracted from the AdditionalProperties dictionary of the direct report.
    • It checks if each property is null or empty and replaces missing values with "Not Available" for clearer output.
    • Finally, it outputs the details for each direct report.
  5. Handle No Direct Reports:
    • If the user has no direct reports, it outputs an appropriate message indicating this fact.

Script Output

PowerShell command fetching user details with expanded direct reports using -Expand parameter

Get Group Membership Details

Here's the Graph PowerShell script that fetches the Group IDs to which the user belongs to with the help of -Expand property

# Retrieve the user and expand the memberOf property
$userWithGroups = Get-MgUser -UserId "9ccc0d2b-ff1f-4d13-9dcf-a42749fd27ba" -Expand "memberOf"
                                
# Output the groups the user is a member of
if ($userWithGroups.MemberOf -ne $null) {
    Write-Output "Member of the following groups:"
    foreach ($group in $userWithGroups.MemberOf) {
        Write-Output "Group ID: $($group.Id)"
    }
} else {
        Write-Output "This user is not a member of any groups."
}

How the Script Works?

  1. Retrieve User and Group Memberships:
    • Get-MgUser is the cmdlet used to fetch user data from the Microsoft Graph.
    • -UserId "9ccc0d2b-ff1f-4d13-9dcf-a42749fd27ba" specifies the unique identifier for the user whose information you want to retrieve.
    • -Expand "memberOf" is crucial in this context. The Expand parameter directs the API to include detailed information about related entities—in this case, all the groups (memberOf) the user is part of. Normally, the memberOf data isn't included in the basic user information fetch and would require a separate request to obtain.
  2. Check if the User Is Part of Any Groups:
    • This checks if the MemberOf property contains any items, indicating that the user is a member of one or more groups.
  3. Loop Through Each Group and Display Group IDs:
    • This loop iterates through each group found in the MemberOf property.
    • For each group, the script extracts and outputs the group's unique identifier (Id).
  4. Handle Case Where No Group Memberships Exist:
    • If the MemberOf property is empty, indicating that the user does not belong to any groups, the script outputs a message stating this fact.

Script Output




Benefits of Using -Expand Parameter


  • Efficiency in Data Retrival: Using the -Expand parameter allows you to retrieve related entities in a single API call rather than making multiple calls to the server. This reduces the total number of requests sent, which can significantly decrease network traffic and improve the overall performance of your application. For instance, retrieving a user and their direct reports or group memberships in one request instead of separate requests for each entity.
  • Minimizes API Latency: Every call to an external API introduces latency. By reducing the number of calls with the -Expand parameter, you also reduce the cumulative latency that can occur with multiple API calls. This is particularly advantageous in performance-sensitive applications where response time is critical..
  • Consistency in Data Fetching: Using -Expand helps in maintaining consistency in the data fetched. When data from related entities is required, fetching it in a single call ensures that the data is synchronized and reflects the state of the database at the time of the query. This avoids potential discrepancies that might occur when making separate calls at different times.
  • Reduces API Quota Usage: Most APIs, including Microsoft Graph, have a quota on the number of calls you can make within a certain period. By using -Expand to retrieve more data per call, you effectively use fewer API calls, which helps in staying within API rate limits and reduces the likelihood of encountering API throttling.
  • Optimized Resource Usage: When you fetch data in fewer calls, you also optimize the usage of server and network resources, both on the client-side and the API provider's side. This can lead to cost savings, especially in cloud environments where resource utilization may directly impact billing.

Frequently Asked Questions (FAQs)

What does the -ExpandProperty parameter do in Graph PowerShell?

The -ExpandProperty parameter retrieves related or nested properties that are not returned by default. It is mainly used when fetching related objects, such as a user's manager, direct reports, or group members.

How is -ExpandProperty different from -Property?

-ExpandProperty fetches related objects in a single request (e.g., fetching a user’s manager along with the user). -Property retrieves additional fields but does not expand related objects.

Can I expand multiple properties at once?

Yes, you can expand multiple properties by separating them with commas.

Get-MgUser -UserId user@example.com -ExpandProperty Manager, DirectReports

How do I get group members using -ExpandProperty?

Use -ExpandProperty Members to get all members of a Microsoft 365 Group:

Get-MgGroup -GroupId  -ExpandProperty Members

This fetches group details along with its members.

What’s the best alternative if -ExpandProperty doesn’t work?

If -ExpandProperty isn’t supported, use a separate API call. For example, if DirectReports is not available, run:

Get-MgUserDirectReport -UserId user@example.com

Related Articles:

Connect to Microsoft 365 Using PowerShell
How to Create Bulk Users in Office 365 Using Graph PowerShell?
Create Microsoft 365 Group Using Microsoft Graph PowerShell
Block Microsoft 365 User Using Microsoft Graph PowerShell
Microsoft 365 User Management Using Graph PowerShell
Assign Microsoft 365 License Using Graph PowerShell
Microsoft 365 User Management Using Graph PowerShell
Checking Group Membership in Microsoft 365
Bulk Assign Microsoft 365 License
Find Inactive Users in Microsoft 365
Using Powershell Graph Search Query

© m365corner.com. All Rights Reserved. Design by HTML Codex