Nested member group count

I have this code:

$SearchBaseOU = "DC=company,DC=com"
$DL_Groups = Get-ADGroup -Filter 'GroupCategory -eq "Distribution"' -SearchBase $SearchBaseOU

$groups = $DL_Groups 
$gm     = @() 

foreach ($group in $groups){
    $gm += Get-ADGroupMember $group -Recursive |
           where {$_.objectclass -eq 'user'}
} 

Write-output "Total: $(($gm.samaccountname | select -Unique).count)"

…but instead of getting every group in my domain, I only want groups (and/or Nested groups) that have >50 members before I filter for unique names.

Where would I insert that restricted requirement?

The group name isn’t being captured. Get that first and then use Group-Object:

$SearchBaseOU = "DC=company,DC=com"
$DL_Groups = Get-ADGroup -Filter 'GroupCategory -eq "Distribution"' -SearchBase $SearchBaseOU
 
$groups = $DL_Groups 
 
$gm = foreach ($group in $groups){
    Get-ADGroupMember $group -Recursive |
    where {$_.objectclass -eq 'user'} |
    Select *, @{Name='GroupName';Expression={$group}}
} 

$gmGrouped = $gm | 
             Group-Object -Property GroupName | 
             Where{$_.Count -ge 50} |
             Select-Object Name, Count, @{Name='CountUnique';Expression={($_.Group | Select-Object SamAccountName -Unique).Count}}

Not tested, but should be close