Manage Microsoft 365 User Contacts Using Graph PowerShell

Managing contacts in Microsoft 365 is an essential task for many organizations, especially when handling large amounts of contact data for specific users. This PowerShell script, powered by Microsoft Graph API, provides an interactive way to perform key contact management tasks: listing, adding, updating, and deleting contacts for a user. The script offers a convenient console-based approach, making it easy for admins to manage user contacts directly from PowerShell.

The Script

# Microsoft Graph API connection
Connect-MgGraph -Scopes "Contacts.ReadWrite"
Write-Host "Connected to Microsoft Graph"

# Prompt for User ID
$userId = Read-Host "Enter the User ID (or UserPrincipalName) of the user"

# Function to list contacts in a tabular format
function List-Contacts {
    Write-Host "Listing contacts for User ID: $userId..."
    $contacts = Get-MgUserContact -UserId $userId
    if ($contacts) {
        $contacts | Select-Object DisplayName, GivenName, Surname, @{Name="Email";Expression={$_.EmailAddresses[0].Address}} | Format-Table -AutoSize
    } else {
        Write-Host "No contacts found for the specified user."
    }
}

# Function to add a new contact
function Add-Contact {
    $displayName = Read-Host "Enter the contact's display name"
    $givenName = Read-Host "Enter the contact's given name"
    $surname = Read-Host "Enter the contact's surname"
    $email = Read-Host "Enter the contact's email address"

    $contactParams = @{
        DisplayName = $displayName
        GivenName = $givenName
        Surname = $surname
        EmailAddresses = @(@{ Address = $email; Name = $displayName })
    }

    $newContact = New-MgUserContact -UserId $userId -BodyParameter $contactParams
    Write-Host "Contact '$displayName' added successfully with ID: $($newContact.Id)"
}

# Function to update an existing contact
function Update-Contact {
    $contactId = Read-Host "Enter the Contact ID of the contact you want to update"
    $newDisplayName = Read-Host "Enter the new display name for the contact (leave blank to skip)"
    $newEmail = Read-Host "Enter the new email address for the contact (leave blank to skip)"

    $updateParams = @{}
    if ($newDisplayName) { $updateParams.DisplayName = $newDisplayName }
    if ($newEmail) {
        $updateParams.EmailAddresses = @(@{ Address = $newEmail; Name = $newDisplayName })
    }

    if ($updateParams.Count -gt 0) {
        Update-MgUserContact -UserId $userId -ContactId $contactId -BodyParameter $updateParams
        Write-Host "Contact updated successfully."
    } else {
        Write-Host "No updates were made."
    }
}

# Function to remove a contact
function Remove-Contact {
    $contactId = Read-Host "Enter the Contact ID of the contact you want to delete"
    $confirmation = Read-Host "Are you sure you want to delete this contact? (y/n)"
    
    if ($confirmation -eq "y") {
        Remove-MgUserContact -UserId $userId -ContactId $contactId -Confirm:$false
        Write-Host "Contact deleted successfully."
    } else {
        Write-Host "Contact deletion canceled."
    }
}

# Main Script Loop
while ($true) {
    Write-Host "`nChoose an action to manage user contacts:"
    Write-Host "1. List Contacts"
    Write-Host "2. Add a Contact"
    Write-Host "3. Update a Contact"
    Write-Host "4. Remove a Contact"
    Write-Host "5. Exit"
    $choice = Read-Host "Enter the number corresponding to your choice"

    switch ($choice) {
        "1" { List-Contacts }
        "2" { Add-Contact }
        "3" { Update-Contact }
        "4" { Remove-Contact }
        "5" { Write-Host "Exiting..."; break }
        default { Write-Host "Invalid choice, please try again." }
    }
}

# Disconnect from Microsoft Graph
Disconnect-MgGraph
Write-Host "Disconnected from Microsoft Graph"

See the Script in Action by clicking and playing this GIF:

How the Script Works

  • Connect to Microsoft Graph: The script starts by connecting to Microsoft Graph with Contacts.ReadWrite permissions, which enable the script to manage user contacts.
  • User ID Prompt: The script prompts the admin to enter the UserId (user's ID or UPN) of the user whose contacts they want to manage.
  • List-Contacts: Displays all contacts in a neat table format, showing fields like DisplayName, GivenName, Surname, and primary Email.
  • Add-Contact: Collects the display name, given name, surname, and email address from the user, and creates a new contact with these details.
  • Update-Contact: Updates the display name or email address of an existing contact by prompting for ContactId and new values.
  • Remove-Contact: Prompts for the ContactId and confirmation before deleting the specified contact.
  • Main Menu: Provides an interactive menu that continuously prompts the user to select an action until they choose to exit.

Further Enhancements

  • Enhanced Validation: Add validation to ensure the entered UserId and ContactId exist, reducing the chance of errors.
  • Logging: Enable logging to track changes made to contacts, which can be useful for audit and compliance purposes.
  • Bulk Import/Export:Extend the script to allow bulk addition or export of contacts, which could simplify contact management for large teams or departments.
  • Detailed Filtering: Include filtering options in the List-Contacts function to allow admins to search contacts based on criteria like name or email domain.

Possible Errors & Solutions

Error Cause Solution
NotFound: Resource not found UserId or ContactId does not exist. Verify UserId and ContactId with Get-MgUser and Get-MgUserContact.
Permission Denied Insufficient permissions. Ensure Contacts.ReadWrite permissions.
InvalidRequest: Invalid Parameter in Body Improper BodyParameter structure. Check BodyParameter formatting for valid properties.

Conclusion

This PowerShell script provides a straightforward, interactive approach to managing user contacts in Microsoft 365. From listing contacts in a tabular format to adding, updating, and removing contacts, the script simplifies contact management tasks for administrators. With additional enhancements, this script can become an even more powerful tool for managing contacts at scale, enabling organizations to improve productivity and streamline user data management in Microsoft 365.


Suggested Reading

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