PowerShell | Exchange Online | Find distribution lists above x members with enabled moderation

1k views Asked by At

I'm trying to export a csv full of Distribution Lists (from Exchange Online) above x members and with enabled moderation.

Problem here is that it's displaying ALL DL's with attributes I'm asking but completely ignoring the "above 100" part and without displaying the total count for each one.

The code I'm using is:

$distgroups = Get-DistributionGroup -ResultSize Unlimited

foreach ($dg in $distgroups)
{

    $Members = Get-DistributionGroupMember $Dg.name -resultsize unlimited

    if ($Members.count -ge 100)
        {
            Get-DistributionGroup -ResultSize Unlimited | select DisplayName,ModerationEnabled,AcceptMessagesOnlyFromSendersOrMembers
            (Get-DistributionGroupMember $dg.DisplayName).Count
        }
}
Export-Csv C:\Temp\DLs.csv -UseCulture

Just for clarity, I've previously used this but with the same outcome:

$distgroups = Get-DistributionGroup -ResultSize Unlimited

foreach ($dg in $distgroups)
{
    if ((Get-DistributionGroupMember $dg.DistinguishedName).Count -ge 100)
        {
            Get-DistributionGroup -ResultSize Unlimited | select DisplayName,ModerationEnabled,AcceptMessagesOnlyFromSendersOrMembers
        }
}

Export-Csv C:\Temp\DLs.csv
1

There are 1 answers

0
Daniel On BEST ANSWER

It's a little confusing what you are trying to do, but it looks like you are trying to get a list of distribution lists that have 100 or more members and then export that to csv.

There are a few issues that I can see in your code.

  1. you are calling Get-DistributionGroup more time than you need to. Instead of calling again inside the loop just use the $dg object that you already have
  2. Similar issue 'Get-DistributionGroupMember' and count. Just store the objects the first time so that you do not have to run the command again.
  3. You are not supplying any data to Export-Csv

Revised Code

$distgroups = Get-DistributionGroup -ResultSize Unlimited
        
$distGroupsWith100PlusMembers = foreach ($dg in $distgroups) {
    # Store returned members in $members for later use
    if (($members = Get-DistributionGroupMember $dg.DistinguishedName).Count -ge 100) {
        # why are you getting ALL of the distribution groups again here?
        # Get-DistributionGroup -ResultSize Unlimited | 
        #    Select-Object DisplayName, ModerationEnabled, AcceptMessagesOnlyFromSendersOrMembers

        #use $dg instead
        $dg | Select-Object DisplayName, ModerationEnabled, AcceptMessagesOnlyFromSendersOrMembers
        Write-Host $dg.SamAccountName has $members.count members
    }
}

# Pipe the distribution groups (DisplayName, ModerationEnabled,
# AcceptMessagesOnlyFromSendersOrMembers) 
# found with 100 plus members to export-csv
$distGroupsWith100PlusMembers | Export-Csv C:\Temp\DLs.csv