Finding Stale/Empty Groups in Active Directory

At the day job, we routinely clean out the stale users, but seem to neglect the stale groups - I think the fairest way to start cleaning them up is to see which groups have no members in them, and email their manager asking if they want to keep it. So I came up with something like this: *NOTE: As usual I kept my #commented out code in the script to be able to learn where I had hiccups and how I worked around it.*

#I need to get a list of managers email addresses AND the Dl/Security Group name at the end

#get qad groups with NO managers listed>>:
#Get-QADgroup -sl 0 -Empty $true -ldapFilter '(&(!(managedby=*)))' | Export-Csv noowners.csv

#get a list of all groups with no members that have both a manager and an email addy
$EmptyDLs=get-qadgroup -sl 0 -Empty $true -ldapFilter '((managedby=*)(mail=*))' | select managedby,mail
$DLmail=$EmptyDLs | select mail
$DLmanager=$EmptyDLs |select managedby

#grabs user name from managedby field: 
# (get-qaduser (($peeps[3] -split(",*..="))[2])).mail

#this will pull from the pipe
#get-qaduser (($peeps[3]) -split(",*..="))[2]

#give the csv file we're building a header
$details = New-Object psobject
$details | add-member -name username -value userName -membertype noteproperty
$details | add-member -name ownerEmail -value ownerEmail -membertype noteproperty
$details | add-member -name userOwns -value userOwns -membertype noteproperty
$details |  ConvertTo-Csv -NoTypeInformation | Select-Object -Skip 1 | Out-File emptygroups.csv

#start a count:

#this loop will grab the email address of each manager based on a split
 foreach ($DLManagerName in $DLManager){
$DLManagerInfo=get-qadobject $DLManagerName -IncludedProperties mail |select mail,samaccountname
$DLmanagerEmail=$DLManagerInfo | select mail
$DLManagerSAMAccountName=$DLManagerInfo | select samaccountname
$justName=$dlmanagersamaccountname -replace ("@{SAMAccountName=") -replace ("}")
$justEmail=$dlmanageremail -replace ("@{mail=") -replace ("}")
$theDLowned=$DLmail[$i] -replace ("@{mail=") -replace ("}")
write "$i) hello $justName, I see your email addy is $justEmail and you own $theDLowned"

#put these all in a PSObject and export to a CSV that appends with each loop
$details = New-Object psobject
$details | add-member -name username -value $justName -membertype noteproperty
$details | add-member -name ownerEmail -value $justEmail -membertype noteproperty
$details | add-member -name userOwns -value $theDLowned -membertype noteproperty
$details |  ConvertTo-Csv -NoTypeInformation | Select-Object -Skip 1 | Out-File emptygroups.csv -Append

# used this just to output to a text file and could work, but want it in a more readable CSV like above
#$justname | Out-File ed.txt -Append
#$justemail | Out-File ed.txt -Append 
#$theDLowned | Out-File ed.txt -Append
#"***next entry***" | Out-File ed.txt -append

#now I need to put that into an email format that ties the manager name to the DL name.
@2 years ago