PowerShell to pull all empty DLs with no members

Solution 1:

This never failed me to get the empty DL's

$emptyGroups = foreach ($grp in Get-DistributionGroup -ResultSize Unlimited) {
    if (@(Get-DistributionGroupMember –Identity $grp.DistinguishedName -ResultSize Unlimited).Count –eq 0 ) {
        [PsCustomObject]@{
            DisplayName        = $grp.DisplayName
            PrimarySMTPAddress = $grp.PrimarySMTPAddress
            DistinguishedName  = $grp.DistinguishedName
        }
    }
}
$emptyGroups | Export-Csv 'C:\Users\177626\DLsToRemove4.csv' -NoTypeInformation

The @() forces the Get-DistributionGroupMember results into an array to get an accurat .Count property

Solution 2:

Try this instead.

Get-DistributionGroup -ResultSize Unlimited | ? { (Get-DistributionGroupMember $_.PrimarySMTPAddress | Measure-Object).Count -eq 0 } | select DisplayName,PrimarySMTPAddress | Export-Csv DLsToRemove3.csv

Measure-Object is more reliable when counting objects in an array.

Solution 3:

There's the attribute msExchGroupMemberCount which is maintained by Exchange, so a quicker way is to filter on that attribute using get-adgroup.

get-adgroup -Filter "msExchGroupMemberCount -eq 0" -Properties DisplayName,mail | select DisplayName,mail