Microsoft Graph PowerShell provides a powerful cmdlet, Invoke-MgGraphRequest, that allows you to make direct calls to the Microsoft Graph API. While there are specialized cmdlets for managing Microsoft 365 resources, Invoke-MgGraphRequest offers a flexible way to fetch information - such as Microsoft 365 tenant contacts – by allowing you to make custom Graph API requests.
In this article, we will focus on using Invoke-MgGraphRequest to retrieve contacts info available in your Microsoft 365 tenant.
The syntax to fetch Microsoft 365 tenant contacts using Invoke-MgGraphRequest is as follows:
Invoke-MgGraphRequest -Method GET -Uri "https://graph.microsoft.com/v1.0/contacts"
This example demonstrates how to retrieve all contacts available in your Microsoft 365 tenant. The contact list is stored in the 'value' property which you should loop through to output the contact info.
# Invoke the Microsoft Graph request to fetch contacts
$response = Invoke-MgGraphRequest -Method Get -Uri 'https://graph.microsoft.com/v1.0/contacts'
if ($response.value) {
foreach ($contact in $response.value) {
Write-Output "Contact Details:"
foreach ($key in $contact.Keys) {
Write-Output "$key: $($contact[$key])"
}
Write-Output "`n"
}
} else {
Write-Output "No contacts found or the response does not contain a 'value' property."
}
This script retrieves and displays all contacts available in your tenant.
To fetch a specific contact, use the contact ID in the URI:
Invoke-MgGraphRequest -Method Get -Uri 'https://graph.microsoft.com/v1.0/contacts/{contactId}'
Output: Displays the contact identified by ContactId.
Contacts.Read
or Contacts.ReadWrite
permission.Error | Cause | Solution |
---|---|---|
InvalidAuthenticationToken | The provided access token is missing or invalid. | Authenticate using Connect-MgGraph to obtain a valid token before executing the cmdlet.... |
Request_ResourceNotFound | Invalid or missing contact ID. | Verify the contact ID in your query. |
InsufficientPrivileges | The account or app lacks the required permissions. | Assign the Contacts.Read or Contacts.ReadWrite permission to the app in Azure AD. |
While dedicated cmdlets offer direct management of Microsoft 365 resources, Invoke-MgGraphRequest provides the flexibility to configure custom Graph API calls. By leveraging this cmdlet, administrators can build innovative solutions for their organization. Use this approach to enhance automation workflows, improve user data management, and unlock new opportunities for integrating Microsoft 365 data with external tools.
Start exploring the full potential of Invoke-MgGraphRequest today!
© m365corner.com. All Rights Reserved. Design by HTML Codex