Friday, August 31, 2007

Exchange 2007 powershell - enumerate all members of all distribution groups

Updated 4/22/08 - Fixed missing characters lost in previous upload

So I had a request to generate a report showing all Email Distribution Groups and the members of each group. I'm currently learning PowerShell so it worked out good for practice. My first approach was to just build a generic one for any active directory group and OU, etc but after a few roadblocks I wound up at the right way to build it using the build in exchange 2007 cmdlets.

# Enumerates all members of all Distribution Lists in Exchange 2007. Uses cmdlets from exch2007
# Updated 4/22/08
# By: Gnawgnu

#first get all distributionlists
$dl = get-distributiongroup

#prepare and output file
$currDate = get-date
write-host "Email groups as of: " $currDate | out-file 'c:\temp\emailgroupmembers.txt'


#then enumerate through them all and get all group members.
foreach ($group in $dl) {

$groupName = "Group Name: " + $group.name
write-host $groupName -foregroundcolor Green
write-host "Owner: " $group.ManagedBy.Name -foregroundcolor Green
$groupName | out-file -append 'c:\temp\emailgroupmembers.txt'
$group.ManagedBy.Name | out-file -append 'c:\temp\emailgroupmembers.txt'
$dlgm = get-distributionGroupMember $group.name.ToString()
$dlgm | fw | out-file -append 'c:\temp\emailgroupmembers.txt'

}

Yeah, I know some parts could be optimized more but this script works. Have fun with it.