Getting all Exchange MailContacts that are not in a distribution-group?

Viewed 52

I want to export all Exchange mail contacts that are not in a distribution group. I've tried to make an array with every contact in a distribution group and another array with every contact. Then I compare these two arrays to see where a difference is.

I am using:

$groups = Get-DistributionGroup -ResultSize unlimited
$alldgm = @(foreach($group in $groups){Get-DistributionGroupmember $group | ? {$_.recipienttype -eq 'MailContact' } | select name | sort name })
$allc = @(get-mailcontact | select name | sort name)
Compare-Object $alldgm $allc

But the result isn't what I expected, since it only shows me contacts from the second array AllC.

What am I doing wrong?

1 Answers

When I run your $alldgm assignment, I receive an error. Since that's blank and the $allc variable contains everything, the comparison will show that.

Here's an alternative solution to retrieve what you're looking for:

$groups = Get-DistributionGroup -ResultSize unlimited
$alldgm = $groups | foreach { Get-DistributionGroupMember $_.Identity | Where-Object {$_.RecipientType -eq 'MailContact'} }
$allc = Get-Mailcontact
Compare-Object $alldgm.Name $allc.Name

You can also save the sorting until the very last step:

(Compare-Object $alldgm.Name $allc.Name).InputObject | Sort
Related