Export members of distribution list and its nested groups

895 Views Asked by At

I am trying to create a powershell script that can export the members of a DL to an excel file. It should also check for nested groups, and it there are, list the members of that nested group in a new sheet named as that group. If it can also have the header as the nested group name, it will be good but is not ncessary.

Got a draft but its not working, obviously my reason for being here :)

can the pros please take a look and help me out?

$OutputFile = "DL-Members_$(Get-Date -Format ddMMMyyyy_hhmmss).xlsx"
$GroupName = "[email protected]"

$Members = Get-DistributionGroupMember -Identity $GroupName -RecipientTypeDetails UserMailbox, MailUniversalDistributionGroup, DynamicDistributionGroup, SecurityDistributionGroup

$Excel = New-Object -ComObject Excel.Application
$Workbook = $Excel.Workbooks.Add()
$Sheet = $Workbook.Sheets.Item(1)
$Sheet.Name = "Distribution Group Members"
$Sheet.Cells.Item(1,1) = "Display Name"
$Sheet.Cells.Item(1,2) = "Primary Smtp Address"
$Sheet.Cells.Item(1,3) = "Recipient Type"

$Row = 2
foreach ($Member in $Members)
{
    $Sheet.Cells.Item($Row,1) = $Member.DisplayName
    $Sheet.Cells.Item($Row,2) = $Member.PrimarySmtpAddress
    $Sheet.Cells.Item($Row,3) = $Member.RecipientTypeDetails
    if ($Member.RecipientTypeDetails -eq "MailUniversalDistributionGroup" -or $Member.RecipientTypeDetails -eq "DynamicDistributionGroup" -or $Member.RecipientTypeDetails -eq "SecurityDistributionGroup")
    {
        $NestedMembers = Get-DistributionGroupMember -Identity $Member.PrimarySmtpAddress,RecipientTypeDetails UserMailbox, MailUniversalDistributionGroup, DynamicDistributionGroup, SecurityDistributionGroup
        $NestedSheet = $Workbook.Sheets.Add()
        $NestedSheet.Name = $Member.DisplayName
        $NestedSheet.Cells.Item(1,1) = "Display Name"
        $NestedSheet.Cells.Item(1,2) = "Primary Smtp Address"
        $NestedSheet.Cells.Item(1,3) = "Recipient Type"
        $NestedRow = 2
        foreach ($NestedMember in $NestedMembers)
        {
            $NestedSheet.Cells.Item($NestedRow,1) = $NestedMember.DisplayName
            $NestedSheet.Cells.Item($NestedRow,2) = $NestedMember.PrimarySmtpAddress
            $NestedSheet.Cells.Item($NestedRow,3) = $NestedMember.RecipientTypeDetails
            $NestedRow++
        }
    }
    $Row++
}

$Workbook.SaveAs($OutputFile)
$Excel.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel) | Out-Null

Write-Host "Members of distribution group '$GroupName' have been exported to $OutputFile" -foregroundcolor Green
0

There are 0 best solutions below