PenNerd
PenNerd

Reputation: 23

How to use powershell to return all exchange distribution groups for a user

I'm trying to pull a list of Office365 distribution groups for a specific user using powershell. The following works when I type out (or paste)the captured $DN for the user, but if I capture the $DN and use it as a variable, I cannot get the correct results.

This works:

$mailbox=get-Mailbox [email protected]
$DN=$mailbox.DistinguishedName
$DLs=Get-DistributionGroup -ResultSize Unlimited -Filter {Members -like "CN=Lastname\, First M,OU=domain.onmicrosoft.com,OU=Microsoft Exchange Hosted Organizations,DC=NAMPR02A003,DC=prod,DC=outlook,DC=com"}

These do not:

$DLs=Get-DistributionGroup -ResultSize Unlimited -Filter {Members -like $DN}
$DLs=Get-DistributionGroup -ResultSize Unlimited -Filter {Members -like '$DN'}
$DLs=Get-DistributionGroup -ResultSize Unlimited -Filter {Members -like "$DN"}

Can anybody tell me how to get a variable for $DN to work in the script?

Upvotes: 2

Views: 11541

Answers (3)

Maximus
Maximus

Reputation: 3

Avshalom thanks for this awesome script.

I have added this to clean up the results. Just replace "Domain" with your company's domain.

| Select-Object Name, @{label='PrimarySmtpAddress';expression={$_.PrimarySmtpAddress -replace '@domain.com'}}

Note: the -filter {Members...} may be broken in the get-distributiongroup command. Doesn't seem to accept Members as a filterable property. :(

Upvotes: -1

HankC
HankC

Reputation: 1

One-liner:

Get-DistributionGroup -ResultSize Unlimited -Filter "Members -like ""$((get-Mailbox NT_ID).DistinguishedName)""" | sort name

Upvotes: 0

Avshalom
Avshalom

Reputation: 8889

That's what you need:

$Mailbox=get-Mailbox [email protected]
$DN=$mailbox.DistinguishedName
$Filter = "Members -like ""$DN"""
Get-DistributionGroup -ResultSize Unlimited -Filter $Filter

Get-DistributionGroup are not recognize/expand the filter when it's in a {ScriptBlock}

You should create a $Filter Variable that is not in a {ScriptBlock} but it's inside a "Quotes" from the outside and ""DoubleQuotes"" inside for the variable to expand.

Upvotes: 3

Related Questions