Quantcast
Channel: o365info
Viewing all articles
Browse latest Browse all 375

How to Get Contacts in Microsoft 365 with PowerShell

$
0
0

Contacts are people outside your organization that you can add in Microsoft 365 for better collaboration. To manage these organizational contacts, you need to use the Get-MgContact PowerShell cmdlet. In this article, you will learn how to get contacts in Microsoft 365 with PowerShell.

Contacts in Microsoft 365

Organizational contacts can receive communication from Microsoft 365 users, like emails or calendar invites. However, organizational contacts do not have full access to Microsoft applications such as Outlook or Teams unless they are invited as a guest user.

By default, when you add organizational contacts, they are stored in the global address list (GAL). This makes it easier for Microsoft 365 users to send emails, schedule meetings, or interact with contacts outside the organization.

You can manage organizational contacts in two methods:

  • Microsoft 365 admin center
  • Microsoft Graph PowerShell

Note: A contact can only be a member of a mail-enabled security or distribution group in the Microsoft 365 admin center.

Install Microsoft Graph PowerShell

Before you start, you must Install Microsoft Graph PowerShell module.

Install-Module Microsoft.Graph -Force

Important: Always update to the latest Microsoft Graph PowerShell module version before you run a cmdlet or script to prevent errors and incorrect results.

Connect to Microsoft Graph PowerShell

You need to Connect to Microsoft Graph PowerShell using the scopes below.

Connect-MgGraph -Scopes "OrgContact.Read.All", "Directory.ReadWrite.All"

Get all contact information

To get basic information about contacts.

Get-MgContact -All | Format-Table

The PowerShell output results.

DisplayName    Id                                   Mail                   MailNickname       
-----------    --                                   ----                   ------------       
Darren Parker  0d9de098-cf82-4078-a702-6f47eed9b25f darren.p@fabrikam.com  Darren.Parker      
Darren Parker1 82ac8d52-106e-4875-a984-28304fcdc56f darren.p1@fabrikam.com Darren.Parker1     
Cindy White    8f0ea526-4148-43b1-934e-ea6ddb4ad942 cindyw@gmail.com       Cindy.White 

Use the Get-MgContactDelta cmdlet to retrieve newly created, updated, or deleted organizational contacts.

Get-MgContactDelta -All

The PowerShell output is similar.

DisplayName    Id                                   Mail                   MailNickname
-----------    --                                   ----                   ------------
Darren Parker  0d9de098-cf82-4078-a702-6f47eed9b25f darren.p@fabrikam.com  Darren.Parker
Darren Parker1 82ac8d52-106e-4875-a984-28304fcdc56f darren.p1@fabrikam.com Darren.Parker1
Cindy White    8f0ea526-4148-43b1-934e-ea6ddb4ad942 cindyw@gmail.com       Cindy.White

To get more detailed information about contacts, you need to add the Format-List cmdlet.

Get-MgContact -All | Format-List

The PowerShell output result shows this data for each contact.

Addresses                    : {Microsoft.Graph.PowerShell.Models.MicrosoftGraphPhysicalOfficeAddress}
CompanyName                  : o365info
DeletedDateTime              : 
Department                   : Sales
DirectReports                : 
DisplayName                  : Darren Parker
GivenName                    : Darren
Id                           : 0d9de098-cf82-4078-a702-6f47eed9b25f
JobTitle                     : Assistant
Mail                         : darren.p@fabrikam.com
MailNickname                 : Darren.Parker
Manager                      : Microsoft.Graph.PowerShell.Models.MicrosoftGraphDirectoryObject
MemberOf                     : 
OnPremisesLastSyncDateTime   : 
OnPremisesProvisioningErrors : {}
OnPremisesSyncEnabled        : 
Phones                       : {Microsoft.Graph.PowerShell.Models.MicrosoftGraphPhone, Microsoft.Graph.PowerShell.Models.MicrosoftGraphPhone, Microsoft.Graph.PowerShell.Models.MicrosoftGraphPhone}
ProxyAddresses               : {SMTP:darren.p@fabrikam.com}
ServiceProvisioningErrors    : {}
Surname                      : Parker
TransitiveMemberOf           : 
AdditionalProperties         : {[imAddresses, System.Object[]]}

Get specific contact by their ID

Get specific contact information.

 Get-MgContactById -Ids "0d9de098-cf82-4078-a702-6f47eed9b25f"

The PowerShell output results.

Id                                   DeletedDateTime
--                                   ---------------
0d9de098-cf82-4078-a702-6f47eed9b25f

To get more results about a specific contact, use the Format-List cmdlet.

 Get-MgContactById -Ids "0d9de098-cf82-4078-a702-6f47eed9b25f" | Format-List

The PowerShell output results.

DeletedDateTime      : 
Id                   : 0d9de098-cf82-4078-a702-6f47eed9b25f
AdditionalProperties : {[@odata.type, #microsoft.graph.orgContact], [companyName, o365info], [department, Sales], [displayName, Darren Parker]…}

To expand the additional properties, run the PowerShell command below.

 (Get-MgContactById -Ids "0d9de098-cf82-4078-a702-6f47eed9b25f").AdditionalProperties

The PowerShell output results.

Key                          Value
---                          -----
@odata.type                  #microsoft.graph.orgContact
companyName                  o365info
department                   Sales
displayName                  Darren Parker
proxyAddresses               {SMTP:darren.p@fabrikam.com}
givenName                    Darren
imAddresses                  {}
jobTitle                     Assistant
mail                         darren.p@fabrikam.com
mailNickname                 Darren.Parker
surname                      Parker
addresses                    {System.Collections.Generic.Dictionary`2[System.String,System.Object]}
onPremisesProvisioningErrors {}
phones                       {System.Collections.Generic.Dictionary`2[System.String,System.Object], System.Collections.Generic.Dictionary`2[System.String,System.Object], System.Collections.Generic.Dictionary`2[System.String,System.Obj… 
serviceProvisioningErrors    {}

Get contact manager

To get the organizational contact manager, use the Get-MgContactManager with Get-MgUser cmdlet. Specify the contact ID number in the PowerShell command below.

Get-MgUser -UserId (Get-MgContactManager -OrgContactId "0d9de098-cf82-4078-a702-6f47eed9b25f").Id

The PowerShell output shows that Stephen Hunter is the manager of the contact.

DisplayName    Id                                   Mail                        UserPrincipalName
-----------    --                                   ----                        -----------------
Stephen Hunter a3211243-a151-458d-8aed-0c112d5b02bb Stephen.Hunter@m365info.com Stephen.Hunter@m365info.com

To get the organization manager for all contacts, run the PowerShell command below.

# Get all organizational contacts
$orgContacts = Get-MgContact -All

# Loop through each contact and retrieve the manager's user ID
foreach ($contact in $orgContacts) {
    try {
        # Get the contact manager's ID
        $manager = Get-MgContactManager -OrgContactId $contact.Id -ErrorAction SilentlyContinue
        if ($manager) {
            # Get the user details for the manager
            $user = Get-MgUser -UserId $manager.Id
            Write-Host "Contact: $($contact.DisplayName), Manager: $($user.DisplayName) (UserId: $($user.Id))" -ForegroundColor Green
        }
        else {
            Write-Host "Contact: $($contact.DisplayName) has no manager assigned." -ForegroundColor Yellow
        }
    }
    catch {
        Write-Host "Error processing contact $($contact.DisplayName): $_" -ForegroundColor Red
    }
}

The PowerShell output results.

Contact: Darren Parker, Manager: Stephen Hunter (UserId: a3211243-a151-458d-8aed-0c112d5b02bb)
Contact: Darren Parker1 has no manager assigned.
Contact: Cindy White, Manager: Ken Walker (UserId: 12eefbb2-e5f4-4eec-bd18-df7ca2f1ee6b)

Get groups of a specific contact

To get the groups that a specific contact is a member of, you need to use the Get-MgContactMemberOf including the -OrgContactId parameter.

  1. Specify the contact ID number in line 1
  2. Run the PowerShell script
$contactId = "0d9de098-cf82-4078-a702-6f47eed9b25f"
$contact = Get-MgContact -OrgContactId $contactId
$groupIds = Get-MgContactMemberOf -OrgContactId $contactId | Select-Object -ExpandProperty Id

foreach ($groupId in $groupIds) {
    $group = Get-MgGroup -Filter "id eq '$groupId'"
    if ($group) {
        Write-Host "$($contact.DisplayName) is a member of group $($group.DisplayName)" -ForegroundColor Green
    }
}

The PowerShell output results.

Darren Parker is a member of group Sales Spain

Get all groups details of specific contact

Use the Get-MgContactMemberObject to get all the IDs for groups, administrative units, and directory roles the contact is a member of.

  1. Specify the contact ID number in line 1
  2. Run the PowerShell script
$IDs = Get-MgContactMemberObject -OrgContactId "0d9de098-cf82-4078-a702-6f47eed9b25f" -SecurityEnabledOnly:$false
$IDs | ForEach-Object { (Get-MgDirectoryObject -DirectoryObjectId $_).AdditionalProperties } | Format-Table

The PowerShell output results.

Key                          Value
---                          -----
@odata.context               https://graph.microsoft.com/v1.0/$metadata#directoryObjects/$entity
@odata.type                  #microsoft.graph.group
createdDateTime              2024-01-05T11:20:48Z
creationOptions              {}
description                  Sales Spain
displayName                  Sales Spain
groupTypes                   {}
mail                         SalesSpain1@m365info.com
mailEnabled                  True
mailNickname                 SalesSpain1
proxyAddresses               {smtp:SalesSpain1@ms365info.onmicrosoft.com, SMTP:SalesSpain1@m365info.com}
renewedDateTime              2024-01-05T11:20:48Z
resourceBehaviorOptions      {}
resourceProvisioningOptions  {}
securityEnabled              False
securityIdentifier           S-1-12-1-4201660316-1081112547-148121737-226315435
onPremisesProvisioningErrors {}
serviceProvisioningErrors    {}

Get all nested groups of specific contact

A mail-enabled security group can sometimes contain members such as users, contacts, guests, and other groups. A nested group is a group that is a member of another group.

Use the Get-MgContactTransitiveMemberOf to get all the groups that this contact is a member of, including groups that are nested under.

  1. Specify the contact ID number in line 1
  2. Run the PowerShell script
$contactId = "0d9de098-cf82-4078-a702-6f47eed9b25f"
$contactName = (Get-MgContact -Filter "id eq '$contactId'").DisplayName
$groupIds = (Get-MgContactTransitiveMemberOf -OrgContactId $contactId).Id

$groupNames = [System.Collections.Generic.List[Object]]::new()

foreach ($groupId in $groupIds) {
    $group = Get-MgGroup -Filter "id eq '$groupId'"
    if ($group) {
        $groupNames.Add($group.DisplayName)
    }
}

foreach ($groupName in $groupNames) {
    Write-Host "$contactName belongs to group $groupName" -ForegroundColor Green
}

The PowerShell output shows these results.

Darren Parker belongs to group Sales Spain
Darren Parker belongs to group Sales UK

Check if contact is member of group

To check if a group has a specific contact as a member, you need to use the group Object ID number.

  1. Specify the contact display name in line 1
  2. Specify the group ID number in line 5
  3. Run the PowerShell script
$contact = (Get-MgContact -Filter "DisplayName eq 'Darren Parker'")
$contactId = $contact.Id

$GroupIds = @(
    "e22794cd-7e57-4ef9-a652-0315ac80f8c0",
    "fa703f9c-77e3-4070-8928-d408ab4c7d0d"
)

foreach ($GroupId in $GroupIds) { 
    $IsMember = Confirm-MgContactMemberGroup -GroupIds $GroupId -OrgContactId $contactId 
    if ($IsMember) { 
        $Group = Get-MgGroup -Filter "Id eq '$GroupId'" 
        Write-Host "Contact $($contact.DisplayName) is a member of group $($Group.DisplayName)" -ForegroundColor Green 
    }
    else { 
        $Group = Get-MgGroup -Filter "Id eq '$GroupId'" 
        Write-Host "Contact $($contact.DisplayName) is not a member of group $($Group.DisplayName)" -ForegroundColor Yellow
    } 
}

The PowerShell results show that the contact is only a member of one of these groups.

Contact Darren Parker is not a member of group Finance Spain
Contact Darren Parker is a member of group Sales Spain

To get all the members of a specific group, you need to use Get-MgGroupMember in PowerShell.

Export contacts to CSV file

To export all the contacts in Microsoft 365 to a CSV file using PowerShell, follow these steps:

  1. Create the folders temp and scripts in the (C:) drive if you don’t have them already
  2. Download the Export-M365Contacts.ps1 PowerShell script
  3. Or copy the script below into Notepad and save it as Export-M365Contacts.ps1 file
<#
    .SYNOPSIS
    Export-M365Contacts.ps1

    .DESCRIPTION
    Export Microsoft 365 contacts report.

    .LINK
    o365info.com/get-contacts-microsoft-365-powershell/

    .NOTES
    Written by: ALI TAJRAN
    Website:    o365info.com
    LinkedIn:   linkedin.com/in/alitajran
    X:          x.com/alitajran

    .CHANGELOG
    V1.00, 03/26/2025 - Initial version
#>

# Parameter for the CSV export path
param (
    [string]$CSVPath = "C:\Temp\Contacts.csv"
)

# Initialize a List to store the data
$Report = [System.Collections.Generic.List[Object]]::new()

# Connect to Microsoft Graph API
Connect-MgGraph -Scopes "OrgContact.Read.All" -NoWelcome

# Get properties
$Properties = @(
    'Id',
    'DisplayName',
    'Mail',
    'JobTitle',
    'CompanyName',
    'Department'
)

# Get all guest users along with the properties
$AllUsers = Get-MgContact -All -Property $Properties | Select-Object $Properties

foreach ($User in $AllUsers) {
    # Collect data in a custom object
    $ReportLine = [PSCustomObject]@{
        Id          = $User.Id
        DisplayName = $User.DisplayName
        Mail        = $User.Mail
        JobTitle    = $User.JobTitle
        CompanyName = $User.CompanyName
        Department  = $User.Department
    }
    # Add the report line to the List
    $Report.Add($ReportLine)
}

# Display data using Out-GridView
$Report | Out-GridView -Title "Microsoft 365 Contacts"

# Export data to CSV file
try {
    $Report | Export-Csv -Path $CSVPath -NoTypeInformation -Encoding UTF8
    Write-Host "Script completed. Results exported to $CSVPath." -ForegroundColor Cyan
}
catch {
    Write-Host "Error occurred while exporting to CSV: $_" -ForegroundColor Red
}
  1. Save the Export-M365Contacts.ps1 PowerShell script in the C:\scripts folder
  2. Run PowerShell as administrator and run the Export-M365Contacts.ps1 PowerShell script
C:\scripts\.\Export-M365Contacts.ps1 -CSVPath "C:\temp\Contacts.csv"
  1. The script will output the list of Microsoft 365 contacts information in a separate window (Out-GridView)
Get Contacts in Microsoft 365 with PowerShell Out-GridView
  1. The PowerShell script will also export the Microsoft 365 contacts data to a CSV file in the C:\temp folder
  2. Open the CSV file with an application like Microsoft Excel to see the results
Get Contacts in Microsoft 365 with PowerShell to CSV file

That’s it!

Read more: Bulk import contacts to Microsoft 365 using PowerShell »

Conclusion

You learned how to get contacts with Microsoft Graph PowerShell. To get detailed information about contacts in Microsoft 365, it’s best to use PowerShell. It also allows you to export all contact data to get an overview of all the contacts in your organization.

Did you enjoy this article? You may also like How to Import Google Contacts to Outlook. Don’t forget to follow us and share this article.


Viewing all articles
Browse latest Browse all 375