Active Directory – Exporting all members of a Distribution Group

Following on from the article regarding Active Directory – Exporting all User email addresses this piece addresses exporting distribution group members. Let’s be honest, far too tedious a task if attempted manually. Let alone the extra problems created by nested groups.

The following script makes it a doddle. The thing to bear in mind, like all other scripts that interact with Active Directory, it is necessary to have RSAT(Remote Server Administration Tools) installed on client device executing the script.

So here is the code:

Import-Module ActiveDirectory
$group = read-host "Please Enter Group Name: "

$gm = @()
    
$members = Get-ADGroupMember -Identity $group -Recursive
    ForEach ($member in $members) {
        $memberType = $member.objectClass
           If ($memberType -eq 'user') {
                $gm += $member.name
                }
            }
$gm | Out-File c:\temp\$group.txt

Let’s break it down. First we need to bring in the Active Directory module, without it, none of the AD specific cmdlets will be available:

Import-Module ActiveDirectory

Next, we need to ask which group we are interrogating, the input is assigned to the variable $group:

$group = read-host "Please Enter Group Name: "

As we will be iterating through a group and any nested within it to produce a single response, we really need to create an array to add the results, our array is called $gm:

$gm = @()

The next piece does the heavy lifting, the code iterates through the group stored in $group and adds the values to $gm, unless they are a group object, instead, it iterates through them and adds user objects to $gm. It continues to do this until it comes to the end of $group:

$members = Get-ADGroupMember -Identity $group -Recursive
    ForEach ($member in $members) {
        $memberType = $member.objectClass
           If ($memberType -eq 'user') {
                $gm += $member.name
                }
            }

Finally, it is useful to have the results in a nice neat file for later reference or reuse:

$gm | Out-File c:\temp\$group.txt