Using Get-MgContact in Graph PowerShell

This guide demonstrates how to use the Get-MgContact cmdlet in Microsoft Graph PowerShell to retrieve contacts from your Azure AD tenant. Learn how to list all contacts, filter by specific criteria, and export contact details with practical examples

The Get-MgContact cmdlet is part of the Microsoft Graph PowerShell module. It is used to retrieve contact information from Microsoft 365. This cmdlet can be used to get details of a specific contact or a list of contacts. In this article, we will explore its syntax, provide usage examples, discuss common errors, and offer some tips for effective usage.


Prerequisites

  • You need one of the following Azure AD roles: Global administrator or Global reader.
  • Install the Graph PowerShell module by running the command: Install-Module Microsoft.Graph -Scope CurrentUser.
  • Connect to Graph PowerShell with the scope 'Contacts.Read' by running the command: Connect-MgGraph -Scopes "Directory.ReadWrite.All".

Syntax

Get-MgContact [-Filter <String>] [-Search <String>] [-Select <String[]>] [-ExpandProperty <String[]>] [-Top <Int32>] [-All] [-ConsistencyLevel <String>] [-CountVariable <String>] [<CommonParameters>]

Parameters

  • -Filter: Filters the results using OData v4 query options.
  • -Search: Searches for contacts that match the given query.
  • -Select: Specifies the properties to include in the response.
  • -ExpandProperty: Expands related entities inline.
  • -Top: Limits the number of results returned.
  • -All: Retrieves all results.
  • -ConsistencyLevel: Sets the consistency level of the request.
  • -CountVariable: Specifies a variable in which to store the total count of objects.

Usage Examples


Example 1: Retrieve all contacts

Get-MgContact -All

This command retrieves all contacts.

Example 2: Retrieve specific properties of all contacts

Get-MgContact -All -Select DisplayName, Id

This command retrieves only the DisplayName and Id properties of all contacts.

Example 3: Filter contacts by display name

Get-MgContact -Filter "displayName eq 'Graham Bell'"

This command retrieves contacts whose display name is 'Graham Bell'.

Example 4: Search for contacts by a keyword

Get-MgContact -Search "displayName:Stewart" -ConsistencyLevel Eventual

This command searches for contacts with the keyword 'Stewart' in their display name.

Example 5: Retrieve a specific number of contacts

Get-MgContact -Top 10

This command retrieves the top 10 contacts.


Cmdlet Tips

  • Performance Optimization: To enhance performance, especially in large directories, use the -Select parameter to specify only the necessary properties. This reduces the amount of data retrieved and processed.
  • Filtering: Use the -Filter parameter to narrow down results, especially useful in large environments.
  • Consistency Level: When performing queries that involve filtering or searching, setting the -ConsistencyLevel parameter to 'eventual' ensures that the results reflect all recent changes. This is particularly useful in environments with frequent updates.
  • Pagination: Combine -Top and -Skip parameters to handle pagination and retrieve large sets of data in manageable chunks.
  • Handling Large Datasets: For directories with a large number of contacts, consider using pagination to manage the data retrieval process. The -Top parameter specifies the number of items to retrieve, and the -Skip parameter allows you to skip a specified number of items. This approach helps in processing manageable chunks of data.
  • Exporting Data: To analyze or share contact information, you might want to export the data to a CSV file. You can combine Get-MgContact with Export-Csv for this purpose. For example:
  • Get-MgContact -All | Select-Object DisplayName, Mail | Export-Csv -Path "C:\Contacts.csv" -NoTypeInformation

    This command retrieves all contacts, selects the 'DisplayName' and 'Mail' properties, and exports the data to a CSV file at the specified path.


Use-Cases

  1. Managing External Contacts for Communication:
    • Scenario: Organizations often need to manage external contacts, such as vendors, partners, or clients, within their Microsoft 365 environment. These contacts might need to be regularly updated or referenced for communication purposes.
    • Implementation: Use Get-MgContact to retrieve a list of external contacts stored in Azure AD. You can query for contact details such as email addresses, display names, and phone numbers to ensure that communication with external parties remains seamless.
    • Benefit: Centralizes external contact management, ensuring that team members can easily access and communicate with external stakeholders from within Microsoft 365 tools like Outlook and Teams.

  2. Auditing Contact Information for Accuracy:
    • Scenario: Over time, external contact details can become outdated due to personnel changes or company restructuring at partner organizations.
    • Implementation: Use Get-MgContact to audit and review external contacts, ensuring that all information (e.g., email addresses, company names, phone numbers) is accurate and up to date. This is especially useful for large organizations that maintain many external partnerships.
    • Benefit: Keeps external contact information reliable, reducing the risk of communication failures due to incorrect or outdated contact details.

  3. Generating Reports for External Contact Management:
    • Scenario: Organizations may want to generate reports detailing all external contacts to better manage relationships with vendors and partners or to review their communication network.
    • Implementation: Use Get-MgContact to retrieve all contacts and export the data to a CSV or Excel file, allowing for comprehensive reporting and analysis of external contacts. This is helpful for departments like procurement or legal that need a clear overview of communication lines with external entities.
    • Benefit: Provides visibility into the organization's external contact network, aiding in decision-making related to vendor management and external communications.

  4. Automating Contact Directory Updates:
    • Scenario: External contacts may change frequently, especially for businesses that work with a variety of third-party providers. Manually updating contact information can be time-consuming and prone to errors.
    • Implementation: Use Get-MgContact in an automated script to regularly fetch and synchronize external contacts with another system or directory. For instance, you could automatically retrieve external contact information from a CRM system and sync it with Azure AD to keep the directory current.
    • Benefit: Streamlines the contact management process, reducing manual intervention and ensuring that external contacts remain accurate and up to date across systems.


Possible Errors and Solutions


Error: Authentication Issues

Cause: "Authorization_RequestDenied"

Solution: Ensure you have the necessary permissions to access the Microsoft Graph API. You might need to consent to the required permissions or update your access token.

Error: Invalid Filter Syntax

Cause: "Invalid filter clause"

Solution: Check the syntax of your filter. Ensure you are using valid OData v4 query options. Refer to the OData query documentation for details.

Error: Resource Not Found

Cause: "Resource not found"

Solution: Verify that the contact you are trying to retrieve exists. Check for typos or incorrect identifiers.

Error: Throttling

Cause: "Too Many Requests"

Solution: Implement retry logic with exponential backoff in your scripts to handle throttling. Reduce the frequency of your requests.

function Get-ContactsWithRetry {
    param (
        [int]$RetryCount = 3,
        [int]$DelaySeconds = 5
    )

    $attempts = 0
    $success = $false
    while (-not $success -and $attempts -lt $RetryCount) {
        try {
            $contacts = Get-MgContact -All -Select DisplayName, EmailAddresses
            $success = $true
        } catch {
            $attempts++
            Write-Warning "Attempt $attempts failed. Retrying in $DelaySeconds seconds..."
            Start-Sleep -Seconds $DelaySeconds
        }
    }

    if ($success) {
        return $contacts
    } else {
        throw "Failed to retrieve contacts after $RetryCount attempts."
    }
}

$allContacts = Get-ContactsWithRetry

Error: Timeouts

Cause: "Request timeout"

Solution: Increase the timeout value for your request. Optimize your queries to return only the necessary data.


Frequently Asked Questions

  • 1. What is Get-MgContact used for?
    Get-MgContact is a Microsoft Graph PowerShell cmdlet used to retrieve details about contacts stored in Azure AD, such as their display names, email addresses, and phone numbers.
  • 2. Can I filter contacts by their company name?
    Yes, use the -Filter parameter to filter by properties like CompanyName. Example:
    Get-MgContact -Filter "CompanyName eq 'Contoso'"
  • 3. How can I export contact details to a CSV file?
    Use this script to export contact details like display name, email, and company:
    $Contacts = Get-MgContact -All
    $Contacts | Select-Object DisplayName, EmailAddresses, CompanyName | Export-Csv -Path "C:\Path\To\Contacts.csv" -NoTypeInformation
  • 4. What permissions are required to retrieve contacts?
    You need the Contacts.Read or Contacts.ReadWrite permission in Microsoft Graph PowerShell. Ensure appropriate permissions are granted in Azure AD.
  • 5. How can I retrieve contacts with a specific job title?
    Use the -Filter parameter to specify the job title. For example:
    Get-MgContact -Filter "jobTitle eq 'Manager'"
    This command retrieves contacts whose job title is 'Manager'.
  • 6. Is it possible to retrieve contacts in a specific department?
    Yes, you can filter contacts by department using the -Filter parameter:
    Get-MgContact -Filter "department eq 'Sales'"
    This command retrieves contacts in the 'Sales' department.
  • 7. How do I retrieve contacts with a specific email domain?
    Use the -Filter parameter with the startswith function:
    Get-MgContact -Filter "startswith(mail, 'user@domain.com')"
    This command retrieves contacts with email addresses starting with 'user@domain.com'.
💡 Contacts Are External and Managed Separately from Users

The Get-MgContact cmdlet is used to retrieve organizational contacts — not Azure AD users.

These contacts are typically external individuals added to the directory for visibility or email routing purposes. They don’t have sign-in access and cannot be licensed like internal users.
💡 Retrieve Custom Fields Like companyName or department Using -Property

By default, Get-MgContact returns a basic set of properties. To retrieve specific contact details — like companyName, department, or businessPhones — use the -Property parameter to customize your query output.

Conclusion

The Get-MgContact cmdlet is a powerful tool for retrieving contact information in Microsoft 365. By leveraging various parameters like -Filter, -Select, and -ExpandProperty, administrators can efficiently manage and access detailed contact data. Ensure the necessary permissions and roles are assigned to avoid access issues.


Related Articles:

Using Get-MgDirectoryRole in Graph PowerShell
Using Get-MgUserLicenseDetail in Graph PowerShell
Using Find-GraphMgCommand in Graph PowerShell
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
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
Using Powershell Graph Filter Query
Using Where-Object In Graph PowerShell
Using Expand Property In Graph PowerShell
Using Select Object In Graph PowerShell
Using -Contains Operator In Graph PowerShell
Add User to Multiple Microsoft 365 Groups Using Graph PowerShell
Get Microsoft 365 User Location Using Graph PowerShell
Import Microsoft 365 Groups from CSV File Using Graph PowerShell
Microsoft 365 Group User Import Using Graph PowerShell

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