List all Corporate Contacts and Distribution Lists they belong to

0

There are times when your company needs to keep a list of Corporate Contacts that are used by your own users on a daily basis.

You can find them in Microsoft 365 Admin Center – Users – Contacts or Exchange Admin Center – Recipients – Contacts.

It gets more complicated when those contacts are added to several Distribution Lists, more so when they are mixed with your users.

The issue is that unlike working with Internal Users, you cannot open a contact and see which groups it belongs to.

This is where PowerShell comes handy.

The script below finds every single contact and all groups it belongs to (if any).

To show the result I use a Grid View (Out-GridView) because it provides an easy column sorting and filtering.

This script might help to find a user error if some contact should or should not be in a group.

Side note: a PowerShell script can become really overwhelming if one adds more and more conditions, error handling and so on. Instead I’ll try to focus on the gist of them rather than polishing to an unreasonable degree.

$answer = Read-Host "Would you like to list all external contacts and groups they belong to ( y / n )?"

While ("y","n" -notcontains $answer) {
	$answer = Read-Host "Would you like to list all external contacts and groups they belong to ( y / n )?"
}

If ($answer -eq 'y') {

	$collection = @()
	$contacts = Get-MailContact -ResultSize unlimited
	
	ForEach($contact in $contacts) {
        
		$DN=$contact.DistinguishedName
		$Filter = "Members -like '$DN'"
		$groups = Get-DistributionGroup -ResultSize unlimited -Filter $Filter

		$outObject = "" | Select "Full Name","Email","Groups"

		$outObject."Full Name" = $contact.DisplayName
		$outObject."Email" = $contact.PrimarySMTPAddress
		$outObject."Groups" = $groups

		$collection += $outObject

	}

	$collection | Out-GridView

	Remove-Variable * -ErrorAction SilentlyContinue
	
}
	
Else {
	Remove-Variable * -ErrorAction SilentlyContinue
}
0

Leave a Reply

Close Menu