Skip to content

Export distribution group members to CSV with PowerShell

How to export distribution group members to CSV file? We want a list of all distribution groups and all members of the group. In this article, you will learn how to bulk export distribution group members to CSV file with PowerShell script.

Introduction

A distribution group, or distribution list, is a collection of two or more people that appears in your organization’s address book. When an email message is sent to a distribution group, it goes to all group members.

You want to see which users are members of the distribution groups, also known as distribution lists. The Export-DistributionGroups.ps1 PowerShell script will run against every distribution group.

These groups are:

  • Distribution group
  • Security group (mail-enabled security groups)

Get distribution group members with PowerShell script

The Export-DistributionGroups.ps1 PowerShell script works for Exchange Server and will get all the distribution groups, including their members, and export them to a CSV file.

The script will gather the following information per distribution group:

  1. DisplayName
  2. PrimarySmtpAddress
  3. SecondarySmtpAddress
  4. Alias
  5. GroupType
  6. RecipientType
  7. Member
  8. MemberPrimarySmtpAddress
  9. MemberType
  10. MemberAccountStatus
  11. Owners
  12. HiddenFromAddressLists
  13. MemberJoinRestriction
  14. MemberDepartRestriction
  15. RequireSenderAuthenticationEnabled
  16. AcceptMessagesOnlyFrom
  17. Notes
  18. SendOnBehalf
  19. SendAs
  20. DateCreated
  21. DateModified

Note: Do you want to get a list of all the distribution group members in Exchange Online? Read the article Export Microsoft 365 distribution group members to CSV with PowerShell.

Prepare export distribution groups PowerShell script

Create two folders on the (C:) drive:

  • Temp
  • Scripts

Download the Export-DistributionGroups.ps1 PowerShell script and place it in C:\scripts folder. The script will export the CSV file to the C:\temp folder.

Ensure the file is unblocked to prevent errors when running the script. Read more in the article Not digitally signed error when running PowerShell script.

Another option is to copy and paste the below code into Notepad. Give it the name Export-DistributionGroups.ps1 and place it in the C:\scripts folder.

<#
    .SYNOPSIS
    Export-DistributionGroups.ps1

    .DESCRIPTION
    Export Exchange Server Distribution Group Members to CSV file with PowerShell.

    .LINK
    www.alitajran.com/export-distribution-group-members-to-csv/

    .NOTES
    Written by: ALI TAJRAN
    Website:    www.alitajran.com
    LinkedIn:   linkedin.com/in/alitajran

    .CHANGELOG
    V1.00, 06/06/2021 - Initial version
    V2.00, 04/13/2024 - Refactored and added more properties
    V2.10, 04/19/2024 - Fixed contact error, SendAs permissions not working, and added MemberType property
#>

# CSV file export path
$Csvfile = "C:\temp\ExportDGs.csv"

# Get all distribution groups
$Groups = Get-DistributionGroup -ResultSize Unlimited

# Create an empty array to store the custom objects
$Results = @()

# Set up the progress bar parameters
$totalGroups = $Groups.Count
$currentGroup = 0

# Loop through distribution groups
foreach ($Group in $Groups) {

    $GroupDN = $Group.DistinguishedName
    $DisplayName = $Group.DisplayName
    $PrimarySmtpAddress = $Group.PrimarySmtpAddress
    $SecondarySmtpAddresses = $Group.EmailAddresses | Where-Object { $_ -clike "smtp*" } | ForEach-Object { $_ -replace "smtp:", "" }
    $GroupType = $Group.GroupType
    $RecipientType = $Group.RecipientType
    $Members = Get-DistributionGroupMember $GroupDN -ResultSize Unlimited
    $ManagedBy = $Group.ManagedBy
    $Alias = $Group.Alias
    $HiddenFromAddressLists = $Group.HiddenFromAddressListsEnabled
    $MemberJoinRestriction = $Group.MemberJoinRestriction
    $MemberDepartRestriction = $Group.MemberDepartRestriction
    $RequireSenderAuthenticationEnabled = $Group.RequireSenderAuthenticationEnabled
    $AcceptMessagesOnlyFrom = $Group.AcceptMessagesOnlyFromSendersOrMembers
    $SendOnBehalf = $Group.GrantSendOnBehalfTo
    $Notes = (Get-Group $GroupDN)
    $DateCreated = $Group.WhenCreated
    $DateModified = $Group.WhenChanged

    # Get SendAs permissions
    $SendAsPermissions = Get-ADPermission $($Group.identity) |
    Where-Object {
        ($_.ExtendedRights -like "*send-as*") -and
        ($_.IsInherited -like "false") -and
        ($_.User -notlike "NT Authority\self")
    }
    $SendAsUsers = $SendAsPermissions.User

    # Loop through each member and add them to the results array
    foreach ($Member in $Members) {
        $AccountStatus = $null
        if ($Member.RecipientType -ne "MailContact") {
            $AccountStatus = (Get-ADUser -Identity $Member.DistinguishedName -ErrorAction SilentlyContinue).Enabled
        }
        else {
            $AccountStatus = "N/A"
        }

        $Result = [PSCustomObject]@{
            DisplayName                        = $DisplayName
            PrimarySmtpAddress                 = $PrimarySmtpAddress
            SecondarySmtpAddress               = ($SecondarySmtpAddresses -join ',')
            Alias                              = $Alias
            GroupType                          = $GroupType
            RecipientType                      = $RecipientType
            Member                             = $Member.Name
            MemberPrimarySmtpAddress           = $Member.PrimarySmtpAddress
            MemberType                         = $Member.RecipientType
            MemberAccountStatus                = $AccountStatus
            Owners                             = ($ManagedBy.Name -join ',')
            HiddenFromAddressLists             = $HiddenFromAddressLists
            MemberJoinRestriction              = $MemberJoinRestriction
            MemberDepartRestriction            = $MemberDepartRestriction
            RequireSenderAuthenticationEnabled = $RequireSenderAuthenticationEnabled
            AcceptMessagesOnlyFrom             = ($AcceptMessagesOnlyFrom.Name -join ',')
            Notes                              = $Notes.Notes
            SendOnBehalf                       = ($SendOnBehalf.Name -join ',')
            SendAs                             = ($SendAsUsers -join ',')
            DateCreated                        = $DateCreated
            DateModified                       = $DateModified
        }

        $Results += $Result
    }
    # Update the progress bar
    $currentGroup++
    $status = "{0:N0}" -f ($currentGroup / $totalGroups * 100)

    $progressParams = @{
        Activity        = "Retrieving Group Members"
        Status          = "Processing group: $($Group.DisplayName) - $currentGroup of $totalGroups : $status% completed"
        PercentComplete = ($currentGroup / $totalGroups) * 100
    }

    Write-Progress @progressParams
}

# Complete the progress bar
Write-Progress -Activity "Retrieving Group Members" -Completed

# Output the custom objects array, sort them, and display in a grid view
$Results | Sort-Object DisplayName | Out-GridView -Title "Exchange Server Distribution Group Members"

# Export report to CSV file
$Results | Sort-Object DisplayName | Export-CSV -Path $Csvfile -NoTypeInformation -Encoding UTF8 #-Delimiter ";"
  • Line 23: Edit the CSV file path if you want

Note: If you want to export a specific distribution group, add the group name in line 26.

$Groups = Get-DistributionGroup "All Staff" -ResultSize Unlimited

Run export distribution groups PowerShell script

Run Exchange Management Shell as administrator and run the PowerShell script to export all distribution groups and members to CSV file.

c:\scripts\.\Export-DistributionGroups.ps1

The Export-DistributionGroups.ps1 PowerShell script starts scanning the distribution groups in the organization. This can take some time.

When it’s done, a list is created and exported in the C:\temp folder with the name ExportDGs.csv.

Result distribution group export CSV file

Let’s look at the CSV export file in the path C:\temp. You should see the ExportDGs.csv file.

Export distribution group members to CSV export file

Open ExportDGs.csv with your favorite application. For example, with Microsoft Excel.

If you don’t need all the information, you can tweak it to your needs. You can sort and filter the columns by DisplayName, GroupType, HiddenFromAddressLists, or any other type.

Export distribution group members to CSV open file

Did this help you to export distribution group members to CSV file with PowerShell?

Read more: Create distribution group in Exchange Hybrid »

Conclusion

You learned how to export distribution group members to CSV with PowerShell. The export to CSV file in Exchange admin center will not give you as much information as PowerShell does. With PowerShell, you can have a custom distribution group report. Use the Export-DistributionGroups PowerShell script.

Did you enjoy this article? You may also like Remove users from group with PowerShell. Don’t forget to follow us and share this article.

ALI TAJRAN

ALI TAJRAN

ALI TAJRAN is a passionate IT Architect, IT Consultant, and Microsoft Certified Trainer. He started Information Technology at a very young age, and his goal is to teach and inspire others. Read more »

This Post Has 30 Comments

  1. Hi Ali,
    Exchange on-premises environment($SendAsPermissions = Get-RecipientPermission -Identity $PrimarySmtpAddress.Address)Don’t have the Get-RecipientPermission command?Does this command only work in Exchange Online environments?

    Thanks !

  2. Hi Ali,

    Thank you

    I need particular only one distribution group report to export it’s possible so please help..

  3. Firstly, the script is very awesome and very helpful, how every I need fewer things to add in the script, firstly on what date the distribution group is been created as well as last modification date. Secondly, how to add total members count into this script. Thirdly, we need html report for IT audit purpose & inventory thus please help me to resolve this.

    Thanks & regards,
    Sandip

  4. Hi Ali dank voor het delen van dit geweldige script.
    Het is me gelukt alle gegevens te exporteren. Zit nu alleen met een uitdaging de gegevens ook in Exchange 365 te importeren maar wat ik ook probeer het lukt me alleen de DL groep, e-mail, owner en members te importeren en niet de andere gegevens die in geëxporteerde CSV staan. Kan jij ons bij staan . Alvast enorm bedankt voor je flexibiliteit.

    Wij zijn bezig te migreren vanuit Exchange 2016 on prem naar Exchange 365

    1. Get the OU distinguishedName and follow the below steps:

      Change lines 25-26 in the script:

      # Get all distribution groups
      $Groups = Get-DistributionGroup -ResultSize Unlimited

      With the below lines:

      # Fill in OU
      $OUScope = "OU=Finance,OU=Company,DC=exoip,DC=local"
      
      # Get all distribution groups in OU
      $Groups = Get-DistributionGroup -OrganizationalUnit $OUScope -ResultSize Unlimited
  5. Hi. This script is awesome. Thank you for sharing.

    I’ve been trying to get it to also pull the UPN of the members of each DL without success. Is that possible?

    Maybe you could point me in the right direction?

  6. Really appreciate the work you did on this script, worked a gem for me.
    I performed this script on exchange 2013 OnPrem and now was to use this CSV file to create and import into Exchange Online.

    Is it just a matter of changing get-distribution to new-distribution?

    Or do you have to start from scratch?

    1. It’s already in the script.

      The RequireSenderAuthenticationEnabled parameter specifies whether to accept messages only from authenticated (internal) senders.

      Valid values are:

      True: Messages are accepted only from authenticated (internal) senders. Messages from unauthenticated (external) senders are rejected.
      False: Messages are accepted from authenticated (internal) and unauthenticated (external) senders.

  7. This script is exactly what i needed. thank you! i was doing manual scripts with seperate steps.

    is there a way to use the results to create distribution lists on Exchange Online using the same attributes exported initially?

    we are trying to remove the on-prem DL’s, and recreating them on Exchange Online. i am struggling especially with adding the members to the groups in bulk when it exports with seperation char “,” .

    the exported results are exactly what i want created aswell when creating the DL’s on Exchange online

  8. Hi ALI TAJRAN. thx for the PS script… is there a way to add the description of the DG’s in the ps script. thx

  9. Great script!
    Any advice on how you would go about using something like this to add a batch of staff to new distribution lists?

  10. How can I add more attributes?
    I want to extract with member, Title, Owner, and count of the people added in DL.
    Please help me with this.

  11. I have a similar question as Stanley Dmello up above has, do you have a similar script for importing it? I am wanting to Export from O365 and import it to Exchange On Prem – Exchange Admin Center.

  12. Hi Ali,
    Elegant script! Works great, thank you.
    Any chance you can help me with a modification?
    I’d like to run this against a csv containing a curated list of distros, instead of against every distro in the domain.
    I can set the csv up anyway that makes this easy.
    Thanks,
    Ken

  13. really great script and it worked for me but I didnt get all the other sub domains groups. What it show only the exchange domain only. what I need to have the groups for all the subdomains also … Thanks.

  14. Hi Ali,
    Thanks for sharing this script. Do you have similar script to import all the Distribution groups using this exported data with all the information like members, managedby, SMTP address, Sender restrictions etc.

Leave a Reply

Your email address will not be published. Required fields are marked *