none
Powershell command to list all distribution groups and members of those groups.

    Question

  • I have been tasked with listing all of the distribution groups in our org and showing all members of every group.

    I have tired using get-distributiongroup | get-distributiongroupmember

    But it only show the members and not the groups.  Any scripters out there got a quick one liner I could use?  I really don't want to have to go through all 200 distribution groups manually exporting members to a .csv for each group.

    Thanks in advance!

    Monday, November 02, 2009 9:59 PM

Answers

  • This works on my SBS 2008 box. Nice if anybody out there could test the script as well. There are some quirks with PowerShell v1 (and my thinking). You can easily add a Write-Host $_ before the For loop and Write-Host $member inside the For loop to get screen output or just see what is going on.  

     

    # Initialize array with two fields:

    # Distribution group, Members

    $totalObj = @()

     

    # Retrieve all DGs

    $temp = Get-DistributionGroup -ResultSize Unlimited | 

          

           # Loop through all distribution groups

           ForEach-Object {          

          

                 # Add the members of the DG to an array

                 [array]$mem = Get-DistributionGroupMember -id $_     

                

                 # Loop through the DG and assign each member name to the variable $member

                 for ($i = 0; $i -lt $mem.Count; $i++) {

                        $member = $mem[$i].name

                       

                        # Create instance of object of type .NET

                        $obj = New-Object System.Object

          

                        # Add the name of the DG to the object

                        $obj | Add-Member -MemberType NoteProperty -Value $_.Name -Name 'Distribution Group' -Force

                       

                        # Add the member name to the object

                        $obj | Add-Member -MemberType NoteProperty -Value $member -Name 'Members' -Force -PassThru

                       

                        # Add the object to the array

                        $totalObj += $obj

                 }

           }

     

    # Pipe output to .csv file

    $totalObj | Export-Csv -Encoding 'Unicode' c:\temp\ngtest.csv

     

    The output is written like this to the csv. file:

     

    "Distribution Group",Members

    "All Users","Jon-Alfred Smith"

    "All Users","Julie Smith"

    "Windows SBS Administrators","Standard User with administration links"

    "Windows SBS Administrators","Jon-Alfred Smith"

    If you just want to have the name of the DG once, change this line: Only add the name the first time, when the counter is zero:

     

    # Add the name of the DG to the object

    if ($i -eq 0) {

    $obj | Add-Member -MemberType NoteProperty -Value $_.Name -Name 'Distribution Group' -Force

    }

     



    MCTS: Messaging | MCSE: S+M | Small Business Specialist     

    • Marked as answer by Mike Shen Friday, November 13, 2009 9:24 AM
    Wednesday, November 04, 2009 3:09 PM
  • This is my script:

    usage :
    get-exgrouprecurse <groupname> will display group members and the subgroup on screen

    $group = get-exgrouprecurse <groupname>
    $group |Export-Csv <file name> -NoTypeInformation will export the group members to a file

    #####################################
    #                                   #
    # Script to retreive group members  #  
    #                                   #
    #    Karl Mitschke March 7 2008     #
    #                                   #
    #####################################
    
    ######################################
    #  heavily modified from recipe 7.3  # 
    #   in 'Active Directory Cookbook'   #
    #          by Robbie Allen           #
    ######################################
    
    #requires -pssnapin Microsoft.Exchange.Management.PowerShell.Admin
    param($group)
    $UnknownGroup = @{}
    function DisplayMembers($group)
    {
    	$SubGroup = @{}
    	$AllMembers = @()
    	if(!$group)
    	{
    		$group = Read-Host "Enter the groups display name"
    	}
    	if ($group.Contains("'"))
    	{
    		$group = $group.Replace("'",'"')
    	}
    	if ($group -eq "/?")
    	{
    		Write-Host "Usage:"
    		Write-Host ""
    		Write-Host "get-exgrouprecurse -group <group name>"
    		Write-Host ""
    		Write-Host "or get-exgrouprecurse <group name>"
    		Write-Host "Returns an object containing the group member, and the group name."
    		break
    	}
    	
    	$validate = Get-Group $group
    	if ($validate.RecipientTypeDetails.ToString() -match "mail")
    	{
    		$searchGroup = Get-DistributionGroupMember $group
    		if ($searchGroup)
    		{	
    			foreach ($member in $searchGroup)
    			{
    				$membertype = $member.RecipientTypeDetails
    				if($membertype -match "Group")
    				{
    					$samname = $member.SamAccountName.ToString()
    					if ($SubGroup.ContainsKey($samname) -eq $true)
    					{
     						Write-Output "^ already seen group member (stopping to avoid loop)"
    					}
    		         	else
    					{
    						$SubGroup.Add($samname,$member.DisplayName.ToString())
    					}
    				}	
    				else
    				{
    					if($member.PrimarySmtpAddress -and $member.RecipientTypeDetails -notcontains "group")
    					{
    						$obj = new-object psObject
    						$obj | Add-Member -membertype noteproperty -name GroupMember -Value $member
    						$obj | Add-Member -MemberType noteproperty -Name GroupName -Value $group
    						$AllMembers += $obj
    					}					
    				}
    			}
    		}
    		else
    		{
    			$UnknownGroup.add($group,1)
    		}
    		if($SubGroup.Values.Count -gt 0)
    		{
    			foreach ($subGroup in $SubGroup.values)
    			{
    				DisplayMembers $subGroup
    			}
    		}
    		if ($UnknownGroup.Keys.Count -gt 0)
    		{
    			foreach ($LostGroup in $UnknownGroup.keys)
    			{
    				$obj = new-object psObject
    				$obj | Add-Member -membertype noteproperty -name GroupMember -Value "Cannot enumerate group"
    				$obj | Add-Member -MemberType noteproperty -Name GroupName -Value $LostGroup
    				$AllMembers += $obj
    			}
    			$UnknownGroup.Clear()
    		}	
    	}	
    	else
    	{
    		Write-Output "$group does not appear to be mail enabled."
    	}
    	Write-Output $AllMembers 
    }
    DisplayMembers $group

    • Marked as answer by Mike Shen Friday, November 13, 2009 9:24 AM
    Tuesday, November 03, 2009 3:24 PM

All replies

  • If you use Quest Free PowerShell Commands for Active Directory you can do a:

    Get-QadGroup -GroupType "Distribution" | Get-QadGroupMember -Indirect

    http://www.quest.com/powershell/activeroles-server.aspx

    In EMS it's harder, but I can post a script if you'd like,

    Karl
    Monday, November 02, 2009 11:09 PM
  • I have seen the Quest Free PowerShell Commands but we are not using them.  If you wouldn't mind I would really appreciate it if you could post your script.  I would like to see how this works natively in EMS.

    Thank you
    Tuesday, November 03, 2009 1:49 AM
  • Hi,

    Does this help....

    $DGrps = Get-DistributionGroup
    ForEach ($DGrp in $DGrps) {Write-Host DGrp.name -Filepath <yourfilename> -append $GrpMbrs = Get-DistributionGroupMember -id $DGrp
    foreach ($GrpMbr in $GrpMbrs) {Write-Host $GrpMbr.DistinguishedName -Filepath <yourfilename> -append }}


    Nitin Gupta (gupnit) | MVP - Exchange | http://www.nitingupta.in/blogs
    Tuesday, November 03, 2009 2:23 AM
  • This does appear to work but how do I go about outputting the file to somewhere?  I entered C:\data.csv for <yourfilename> but never see the file created and when I create a blank file called C:\data.csv hoping that the data will append to the file it remains empty.

    Thank for your help!
    Tuesday, November 03, 2009 3:12 PM
  • This is my script:

    usage :
    get-exgrouprecurse <groupname> will display group members and the subgroup on screen

    $group = get-exgrouprecurse <groupname>
    $group |Export-Csv <file name> -NoTypeInformation will export the group members to a file

    #####################################
    #                                   #
    # Script to retreive group members  #  
    #                                   #
    #    Karl Mitschke March 7 2008     #
    #                                   #
    #####################################
    
    ######################################
    #  heavily modified from recipe 7.3  # 
    #   in 'Active Directory Cookbook'   #
    #          by Robbie Allen           #
    ######################################
    
    #requires -pssnapin Microsoft.Exchange.Management.PowerShell.Admin
    param($group)
    $UnknownGroup = @{}
    function DisplayMembers($group)
    {
    	$SubGroup = @{}
    	$AllMembers = @()
    	if(!$group)
    	{
    		$group = Read-Host "Enter the groups display name"
    	}
    	if ($group.Contains("'"))
    	{
    		$group = $group.Replace("'",'"')
    	}
    	if ($group -eq "/?")
    	{
    		Write-Host "Usage:"
    		Write-Host ""
    		Write-Host "get-exgrouprecurse -group <group name>"
    		Write-Host ""
    		Write-Host "or get-exgrouprecurse <group name>"
    		Write-Host "Returns an object containing the group member, and the group name."
    		break
    	}
    	
    	$validate = Get-Group $group
    	if ($validate.RecipientTypeDetails.ToString() -match "mail")
    	{
    		$searchGroup = Get-DistributionGroupMember $group
    		if ($searchGroup)
    		{	
    			foreach ($member in $searchGroup)
    			{
    				$membertype = $member.RecipientTypeDetails
    				if($membertype -match "Group")
    				{
    					$samname = $member.SamAccountName.ToString()
    					if ($SubGroup.ContainsKey($samname) -eq $true)
    					{
     						Write-Output "^ already seen group member (stopping to avoid loop)"
    					}
    		         	else
    					{
    						$SubGroup.Add($samname,$member.DisplayName.ToString())
    					}
    				}	
    				else
    				{
    					if($member.PrimarySmtpAddress -and $member.RecipientTypeDetails -notcontains "group")
    					{
    						$obj = new-object psObject
    						$obj | Add-Member -membertype noteproperty -name GroupMember -Value $member
    						$obj | Add-Member -MemberType noteproperty -Name GroupName -Value $group
    						$AllMembers += $obj
    					}					
    				}
    			}
    		}
    		else
    		{
    			$UnknownGroup.add($group,1)
    		}
    		if($SubGroup.Values.Count -gt 0)
    		{
    			foreach ($subGroup in $SubGroup.values)
    			{
    				DisplayMembers $subGroup
    			}
    		}
    		if ($UnknownGroup.Keys.Count -gt 0)
    		{
    			foreach ($LostGroup in $UnknownGroup.keys)
    			{
    				$obj = new-object psObject
    				$obj | Add-Member -membertype noteproperty -name GroupMember -Value "Cannot enumerate group"
    				$obj | Add-Member -MemberType noteproperty -Name GroupName -Value $LostGroup
    				$AllMembers += $obj
    			}
    			$UnknownGroup.Clear()
    		}	
    	}	
    	else
    	{
    		Write-Output "$group does not appear to be mail enabled."
    	}
    	Write-Output $AllMembers 
    }
    DisplayMembers $group

    • Marked as answer by Mike Shen Friday, November 13, 2009 9:24 AM
    Tuesday, November 03, 2009 3:24 PM
  • Thanks for posting your script Karl. 

    In less I am doing something wrong the script still asks that I submit the anme of the group I want to know about.  I need to know this information for all DL Groups at one time.  Is there away to tell the script to give me information about all of my groups?

    Thank you
    Tuesday, November 03, 2009 6:36 PM
  • Try this:

    Get-DistributionGroup -ResultSize unlimited |%{.\get-exgrouprecurse $_.Name}

    I am pretty sure this will not show the name of the main group - like:

    Group A
    has a member  member 1
    and a member Sub Group 1
    Which has a member Member 2

    I could modify it at some point, or perhaps you can follow it and modify it.

    Karl
    Tuesday, November 03, 2009 8:56 PM
  • At a quick glance, Nitin's script should do what you're looking for with a few modifications.  Write-host is what's preventing the output from going to the file like you're trying to accomplish.  You can modify the script to use the re-directors, or just use out-file.  I haven't tested it, but this should work (just fixing a few bits from Nitin's script, but other then that, really just a copy and paste of his post.)

    $DGrps = Get-DistributionGroup
    ForEach ($DGrp in $DGrps) {out-file -inputobject $DGrp.name -Filepath <yourfilename> -append $GrpMbrs = Get-DistributionGroupMember -id $DGrp
    foreach ($GrpMbr in $GrpMbrs) {out-file -inputobject $GrpMbr.DistinguishedName -Filepath <yourfilename> -append }}


    Good luck,
    Dan Holton
    Wednesday, November 04, 2009 12:25 AM
  • Thanks Mate....I have not tested it, I should have mentioned that, thought it should do the trick.
    Nitin Gupta (gupnit) | MVP - Exchange | http://www.nitingupta.in/blogs
    Wednesday, November 04, 2009 2:56 AM
  • This works on my SBS 2008 box. Nice if anybody out there could test the script as well. There are some quirks with PowerShell v1 (and my thinking). You can easily add a Write-Host $_ before the For loop and Write-Host $member inside the For loop to get screen output or just see what is going on.  

     

    # Initialize array with two fields:

    # Distribution group, Members

    $totalObj = @()

     

    # Retrieve all DGs

    $temp = Get-DistributionGroup -ResultSize Unlimited | 

          

           # Loop through all distribution groups

           ForEach-Object {          

          

                 # Add the members of the DG to an array

                 [array]$mem = Get-DistributionGroupMember -id $_     

                

                 # Loop through the DG and assign each member name to the variable $member

                 for ($i = 0; $i -lt $mem.Count; $i++) {

                        $member = $mem[$i].name

                       

                        # Create instance of object of type .NET

                        $obj = New-Object System.Object

          

                        # Add the name of the DG to the object

                        $obj | Add-Member -MemberType NoteProperty -Value $_.Name -Name 'Distribution Group' -Force

                       

                        # Add the member name to the object

                        $obj | Add-Member -MemberType NoteProperty -Value $member -Name 'Members' -Force -PassThru

                       

                        # Add the object to the array

                        $totalObj += $obj

                 }

           }

     

    # Pipe output to .csv file

    $totalObj | Export-Csv -Encoding 'Unicode' c:\temp\ngtest.csv

     

    The output is written like this to the csv. file:

     

    "Distribution Group",Members

    "All Users","Jon-Alfred Smith"

    "All Users","Julie Smith"

    "Windows SBS Administrators","Standard User with administration links"

    "Windows SBS Administrators","Jon-Alfred Smith"

    If you just want to have the name of the DG once, change this line: Only add the name the first time, when the counter is zero:

     

    # Add the name of the DG to the object

    if ($i -eq 0) {

    $obj | Add-Member -MemberType NoteProperty -Value $_.Name -Name 'Distribution Group' -Force

    }

     



    MCTS: Messaging | MCSE: S+M | Small Business Specialist     

    • Marked as answer by Mike Shen Friday, November 13, 2009 9:24 AM
    Wednesday, November 04, 2009 3:09 PM
  • Jon-alfred:
    I was looking for a way on how to do this, and your script was exactly what i was looking for. Thanks!
    Tuesday, November 17, 2009 7:54 PM
  • Can someone help provide some information on how to modify this script?


    I would like the output to show what groups the users belong to. So for Joe Smith, I want to see that he is part of Accounting, NY Office, FAS etc.

    Thursday, May 06, 2010 8:32 PM
  • Can someone help provide some information on how to modify this script?


    I would like the output to show what groups the users belong to. So for Joe Smith, I want to see that he is part of Accounting, NY Office, FAS etc.

    This will work

    Get-DistributionGroup | where { (Get-DistributionGroupMember $_ | foreach {$_.PrimarySmtpAddress}) -contains "user@domain.com

    Put primary smtp address of the mailbox user and it will show all the DLs that user is member of.

    A discussion on it is already in progress here: 

    http://social.technet.microsoft.com/Forums/en-US/exchangesvradmin/thread/6db0cebc-dc14-4c54-ab6c-2cd23b52d5b5

    Although it is one liner off course u can modify it with the scripts posted above by Jon and karl.

    Regards,


    Laeeq Qazi|Team Lead(Exchange + Sharepoint + BES + DynamicsCRM) www.HostingController.com
    • Proposed as answer by Joshua T Wong Thursday, December 02, 2010 4:51 PM
    Thursday, May 06, 2010 9:08 PM
  • Hi,

    Does this help....

    $DGrps = Get-DistributionGroup
    ForEach ($DGrp in $DGrps) {Write-Host DGrp.name -Filepath <yourfilename> -append $GrpMbrs = Get-DistributionGroupMember -id $DGrp
    foreach ($GrpMbr in $GrpMbrs) {Write-Host $GrpMbr.DistinguishedName -Filepath <yourfilename> -append }}


    Nitin Gupta (gupnit) | MVP - Exchange | http://www.nitingupta.in/blogs

    Hi Nitin Gupta,

                thanks for the script.

    Executing just the code:

     

    $DGrps = Get-DistributionGroup
    ForEach ($DGrp in $DGrps) {Write-Host DGrp.name -Filepath <yourfilename> -append $GrpMbrs = Get-DistributionGroupMember -id $DGrp
    foreach ($GrpMbr in $GrpMbrs) {Write-Host $GrpMbr.DistinguishedName -Filepath <yourfilename> -append }}

     

     

     

    I get an output like this:

     

     

    DGrp.name -Filepath c:\Temp\1.txt -append = Get-DistributionGroupMember -id Group1
    -Filepath c:\Temp\1.txt -append
    DGrp.name -Filepath c:\Temp\1.txt -append = Get-DistributionGroupMember -id Group2
    -Filepath c:\Temp\1.txt -append
    DGrp.name -Filepath c:\Temp\1.txt -append = Get-DistributionGroupMember -id Group3
    -Filepath c:\Temp\1.txt -append
    DGrp.name -Filepath c:\Temp\1.txt -append = Get-DistributionGroupMember -id Group4
    -Filepath c:\Temp\1.txt -append
    DGrp.name -Filepath c:\Temp\1.txt -append = Get-DistributionGroupMember -id Group5
    -Filepath c:\Temp\1.txt -append
    DGrp.name -Filepath c:\Temp\1.txt -append = Get-DistributionGroupMember -id Group6
    -Filepath c:\Temp\1.txt -append

     

    What is wrong? Thanks a lot!


    Piero Bacarella - IT Professional - Rome(Italy) - http://www.it-resources.info
    Friday, January 07, 2011 3:30 PM
  • On Fri, 7 Jan 2011 15:30:00 +0000, Piero Bacarella wrote:
     
    >Hi, Does this help.... $DGrps = Get-DistributionGroup ForEach ($DGrp in $DGrps) {Write-Host DGrp.name -Filepath <yourfilename> -append $GrpMbrs = Get-DistributionGroupMember -id $DGrp foreach ($GrpMbr in $GrpMbrs) {Write-Host $GrpMbr.DistinguishedName -Filepath <yourfilename> -append }}
     
    Don't you just love the way HTML munges things? :-(
     
    Besides the formatting, there was a missing "$" in the 1st "ForEach".
    I added semicolons at the end of each statement so they don't all run
    together if you just copy the text.
     
    $DGrps = Get-DistributionGroup;
    ForEach ($DGrp in $DGrps) {
    Write-Host $DGrp.name -Filepath <yourfilename> -append;
    $GrpMbrs = Get-DistributionGroupMember -id $DGrp;
    foreach ($GrpMbr in $GrpMbrs) {
    Write-Host $GrpMbr.DistinguishedName -Filepath <yourfilename> -append
    }
    }
     
    ---
    Rich Matheisen
    MCSE+I, Exchange MVP
     

    --- Rich Matheisen MCSE+I, Exchange MVP
    Friday, January 07, 2011 8:21 PM
  • Hello.

    With write-host won't work for me, so had to change your script, like that.

    $DGrps = Get-DistributionGroup;
    ForEach ($DGrp in $DGrps) {
    $DGrp.name |Out-file -Filepath <Filename>-Append;
    $GrpMbrs = Get-DistributionGroupMember -id $DGrp;
    foreach ($GrpMbr in $GrpMbrs) {
    $GrpMbr.DistinguishedName |Out-file -Filepath <Filename> -Append;
    }
    }

    Monday, March 14, 2011 2:55 PM
  • I know its a couple years later, but I saw this and here is what I use, very quick and simple.

     

    Get-DistributionGroupMember -identity "group name" | ft "PrimarySMTPAddress" >c:\export-list.txt

    -BV

     

    Tuesday, May 10, 2011 2:51 AM
  • Hi All

    I tested that script of O. Brazhko and Note:

    We must save a filename have there's script, eg: c:\AllDistributionGroup.ps1

    Body of script:

    $DGrps = Get-DistributionGroup;
    ForEach ($DGrp in $DGrps) {
    $DGrp.name |Out-file -Filepath c:\DG.csv -Append;
    $GrpMbrs = Get-DistributionGroupMember -id $DGrp;
    foreach ($GrpMbr in $GrpMbrs) {
    $GrpMbr.DistinguishedName |Out-file -Filepath c:\DG.csv -append;
    }
    }

    And then we open short Exchange PowerShell run as Administrator (not check restriction permittion ).

    At point [PS] ... >we can input path and file name script . eg: c:\AllDistributionGroup.ps1

    wait a minutes...

    We can look file result in c:\DG.csv

    Good luck !

     

    Thang.Le

     

     

    • Proposed as answer by Michael Keel Friday, May 03, 2013 12:09 PM
    Friday, June 17, 2011 9:08 AM
  • AD

    get-adgroup -filter {name -like "*"} | ?{$_.groupcategory -eq "distribution"} | % {Get-ADGroupMember $_}

    exchange

    Get-DistributionGroup mygroupname | Get-distributiongroupmember $_ | select name


    Dan

    Wednesday, December 21, 2011 3:54 PM
  • I changed your script. 

    Group Name and other information are same row in a file. 

    Thank you.

    $DGrps = Get-DistributionGroup;
    ForEach ($DGrp in $DGrps) {

    $GrpMbrs = Get-DistributionGroupMember -id $DGrp;
    foreach ($GrpMbr in $GrpMbrs) {
    $DGrp.name+","+$GrpMbr.DisplayName+","+$GrpMbr.Title+","+$GrpMbr.Alias+","+$GrpMbr.WhenMailboxCreated+","+$GrpMbr.DatabaseName+","+$GrpMbr.HiddenFromAddressListsEnabled+","+$GrpMbr.PrimarySmtpAddress+","+$GrpMbr.DistinguishedName+","+$GrpMbr.Identity+","+$GrpMbr.WhenChanged+","+$GrpMbr.WhenCreated |Out-file -Filepath c:\DG1.csv -append; 


    }
    }

    Wednesday, March 07, 2012 3:54 PM
  • Hi,

    How to modify the script so that it can read and retrieve all Email distribution group from the exchange server ? rather than typing it one by one ?


    /* Server Support Specialist */

    Tuesday, March 13, 2012 10:50 PM
  • Hi,

    How to modify the script so that it can read and retrieve all Email distribution group from the exchange server ? rather than typing it one by one ?


    /* Server Support Specialist */

    Hi,

    Most of the scripts mentioned above retrieve all DGs like this:

    $DGrps = Get-DistributionGroup; 
    ForEach ($DGrp in $DGrps)

    {

    }

    When you don't mention any name or identity after Get-DistributionGroup, then it returns all of the DGs, and if you have more than 1000 DGs in your environment, then you have to put -ResultSize Unlimited like this:

    $DGrps = Get-DistributionGroup  -ResultSize Unlimited
    ForEach ($DGrp in $DGrps)

    {

    }

    Regards,


    Laeeq Qazi|Team Lead(Exchange + Sharepoint + BES + DynamicsCRM) www.HostingController.com

    Wednesday, March 14, 2012 2:25 PM
  • thanks for the response,

    by the way I'm trying to modify the following script from http://www.tinyint.com/index.php/2009/05/24/enumerate-distribution-group-members/ 

    so that it accept the looping as per your suggestion but it failed.

    $DGrps = Get-DistributionGroup -ResultSize Unlimited
    ForEach ($DGrp in $DGrps) {
    .\enumerate_groups.ps1 $DGrp -showTree
    }

    can you please assist me here ?

    Thanks once again.


    /* Server Support Specialist */

    Thursday, March 15, 2012 3:34 AM
  • thanks for the response,

    by the way I'm trying to modify the following script from http://www.tinyint.com/index.php/2009/05/24/enumerate-distribution-group-members/ 

    so that it accept the looping as per your suggestion but it failed.

    $DGrps = Get-DistributionGroup -ResultSize Unlimited
    ForEach ($DGrp in $DGrps) {
    .\enumerate_groups.ps1 $DGrp -showTree
    }

    can you please assist me here ?

    Thanks once again.


    /* Server Support Specialist */

    Hi,

    Please try replacing this line

    \enumerate_groups.ps1 $DGrp -showTree

    with

    \enumerate_groups.ps1 $DGrp.Identity -showTree

    or

    with

    \enumerate_groups.ps1 $DGrp.DistinguishedName -showTree

    Regards,


    Laeeq Qazi|Team Lead(Exchange + Sharepoint + BES + DynamicsCRM) www.HostingController.com

    Saturday, March 17, 2012 8:14 PM
  • I just used this on a Windows 2008 R2 server running Exchange 2010.  I noticed that I was getting a bunch of pipe errors stating that the next command couldn't be run because a pipe command was already in progress.

    I added "Start-Sleep -ms 500" statements here:

    # Loop through all distribution groups
           ForEach-Object {

          
    Start-Sleep -m 500  

    And here:

    # Loop through the DG and assign each member name to the variable $member
                 for ($i = 0; $i -lt $mem.Count; $i++) {

                        
    Start-Sleep -m 500
                        $member = $mem[$i].name

    and that seemed to fix it!

    Thanks Jon, this saved me a bunch of time!


    Thursday, May 17, 2012 7:38 PM
  • Worked for me!  Thanks!
    Tuesday, June 19, 2012 12:30 AM
  • Karl,

    I've used a few of your scripts now but THIS one saved me hours of hurting. 

    I only needed to add $group.PrimarySmtpAddress and $.group.DisplayName to the below values to get everything I needed.

    						$obj | Add-Member -membertype noteproperty -name GroupMember -Value $member
    						$obj | Add-Member -MemberType noteproperty -Name GroupName -Value $group
    						$AllMembers += $obj
    My DL was easily Fifty DL's deep and it got it all.<br/>Thank you very much.

    Scott




    • Edited by y2kc0wb0y Monday, October 01, 2012 3:30 PM
    Monday, October 01, 2012 3:29 PM
  • Scott;

    Glad to help, and glad you found it useful :)

    Karl


    When you see answers and helpful posts, please click Vote As Helpful, Propose As Answer, and/or Mark As Answer



    My Blog: http://unlockpowershell.wordpress.com
    My Book: Windows PowerShell 2.0 Bible
    My E-mail: -join ("6B61726C6D69747363686B65406D742E6E6574"-split"(?<=\G.{2})",19|%{[char][int]"0x$_"})

    Monday, October 01, 2012 4:01 PM
  • I have a small code that has always worked ...

    # Start

    # define destination file

    $saveto = "C:\\temp\\listmembers5.txt"

     

    # Gets all distribution groups

    Get-DistributionGroup | sort name | ForEach-Object {

    "`r`n`r`n======================================" | Add-Content $saveto

    "$($_.Name + "" - "" + $_.PrimarySMTPAddress)`r`n======================================" | Add-Content $saveto

    # Gets all distribution group members

            Get-DistributionGroupMember $_ | sort Name | ForEach-Object {

    # You can edit this to add contacts as well 

                   If($_.RecipientType -eq "UserMailbox")

                            {

                                    $_.Name + " (" + $_.PrimarySMTPAddress + ")" | Add-Content $saveto

                            }

            }

    }

    # end

    Tuesday, March 05, 2013 12:31 PM
  • Thanks Thang.Le, that worked for me.

    I did have to modfiy to add -resultsize unlimited:

    $DGrps = Get-DistributionGroup -ResultSize Unlimited;
    ForEach ($DGrp in $DGrps) {
    $DGrp.name |Out-file -Filepath c:\DG.csv -Append;
    $GrpMbrs = Get-DistributionGroupMember -id $DGrp;
    foreach ($GrpMbr in $GrpMbrs) {
    $GrpMbr.DistinguishedName |Out-file -Filepath c:\DG.csv -append; }}

    Friday, May 03, 2013 1:45 PM
  • I've just uploaded a script I've been using for a while to the gallery: http://gallery.technet.microsoft.com/Get-DistributionGroupMember-978af348. As I said in the description, it was one of my first foray's into advanced functions so it may be a bit rough around the edges but I've been using it for a while without any (perceived) issues. I hope it works for you but let me know if you notice any problems. Thanks, Mark.
    Thursday, May 16, 2013 5:03 PM
  • Lets assume the situation,

    You need to export all the distribution groups from exchange servers and the members of that group. To do that you just need to use two power shell command with to "ForEach" loop.

    =================

     

    $DGs = Get-DistributionGroup
    $Heading = "Group Name" + "\" + "Members"

    ForEach ($DG in $DGs)
    {
    $GroupName = $DG.DisplayName
    $Members = Get-DistributionGroupMember "$DG"

    ForEach ($Member in $Members)
    {
    $DisplayName = $Member.DisplayName
    $Output = "$GroupName" + " \ " + "$DisplayName"
    $Output
    }


    }

    ==================================================

    This will export the groups with membership.

    Hope this helps

    Tuesday, June 11, 2013 9:28 PM
  • I found the sleep timer worked in very small environments, but in large environments (1000+ DL's), it simply didn't work. The answer is to not pipe the command directly, but first pass it to a variable so it is loaded in memory, then pipe the variable. With this, no "Start-Sleep" pauses are neccisary. Here's my full code. This worked flawlessly.

    # Initialize array with two fields:
    # Distribution group, Members
    $totalObj = @()
    # Retrieve all DGs
    $temp = Get-DistributionGroup -ResultSize Unlimited 
    
           # Loop through all distribution groups
           $temp | ForEach-Object { 
    
                 # Add the members of the DG to an array
                 [array]$mem = Get-DistributionGroupMember -id $_     
    
                 # Loop through the DG and assign each member name to the variable $member
                 for ($i = 0; $i -lt $mem.Count; $i++) {
    
                        $member = $mem[$i].name
    
                        # Create instance of object of type .NET
                        $obj = New-Object System.Object
    
                        # Add the name of the DG to the object
    		    if ($i -eq 0) {
                           $obj | Add-Member -MemberType NoteProperty -Value $_.Name -Name 'Distribution Group' -Force
                        }
                        # Add the member name to the object
                        $obj | Add-Member -MemberType NoteProperty -Value $member -Name 'Members' -Force -PassThru                
                        # Add the object to the array
                        $totalObj += $obj
                 }
           } 
    # Pipe output to .csv file
    $totalObj | Export-Csv -Encoding 'Unicode' DL_Members.csv
    

    Wednesday, November 13, 2013 10:44 PM
  • This worked a treat, thanks
    Monday, February 03, 2014 4:49 PM