Advanced Windows PowerShell Scripting Video Training

Advanced Windows PowerShell Scripting Video Training
Advanced Windows PowerShell Scripting Video Training

Monday, February 25, 2013

How to list all members of a Distribution group and their emails with PowerShell

This question came from the need of a user who needed to extract the following information:

Distribution Group Name | Group Email | Group Member | Member’s Email

 

Function Get-DistributionEmail

{

 

    # Get a list of all the distribution groups in the domain.

    $Groups = Get-ADGroup -Filter 'GroupCategory -eq "Distribution"' -Properties Mail

 

    # Create a dynamic array to hold the objects for the output.

    $Obj = @()

   

    # Loop through each group.

    ForEach ($Group in $Groups)

    {

        # Enumerate all the members of the group.

        $Members = Get-ADGroupMember -Identity $Group.name

       

        # Collect the data for the output.

        ForEach ($Member in $Members)

        {

            $GroupObj = New-Object PSObject

            $GroupObj | Add-Member `

             -MemberType NoteProperty `

             -Name "Group" `

             -Value $Group.Name

           

            $GroupObj | Add-Member `

             -MemberType NoteProperty `

             -Name "GroupEmail" `

             -Value $Group.Mail

 

            $GroupObj | Add-Member `

             -MemberType NoteProperty `

             -Name "User" `

             -Value $Member.Name

           

            $User = get-ADuser -filter 'Name -eq $Member.name' -Properties Mail

 

            $GroupObj | Add-Member `

             -MemberType NoteProperty `

             -Name "UserEmail" `

             -Value $User.Mail

 

             # Transfer the object to the dynamic array.

             $Obj += $GroupObj

        }

    }

    # Wrtie the contents of the array to the PowerShell pipeline.

    Write-Output $Obj | FT -AutoSize

<#

.SYNOPSIS

Gather all user accounts and email addresses of Distribution Group members.

 

.DESCRIPTION

Gather all user accounts and email addresses of Distribution Group members.

 

.EXAMPLE

Get-DistributionEmail

 

Group  GroupEmail      User  UserEmail    

-----  ----------      ----  ---------    

Group1 Group1@Indy.com User1 User1@Indy.com

Group1 Group1@Indy.com User2 User2@Indy.com

Group2 Group2@indy.com User3 User3@indy.com

Group2 Group2@indy.com User4 User4@indy.com

 

.NOTES

Requires the Active Directory module to be available.

#>

}

1 comment:

Biller said...

Cool ! I like it.