Script to get a distribution list membership easily

Throughout my years as a System Administrator, I’ve been asked repeatedly to produce a list for someone of the contents of a distribution list. I searched and found some scripts out there and ended up modifying one that now fits my needs.

# Gets distribution list members from a group in exchange
# Author: Ed Rockwell
# Company: Some Company You Work At
# Date: Today :)
# Ver: 1.0
 
param (
	$OutputFile = "C:\listmembers.txt"
	)
 
Write-Host "Checking if output file already exists..." -NoNewline
 
if (Test-Path $OutputFile)
	{
		Write-Host "Found old output file from last run!"
		Write-Host "Removing old output file..." -NoNewline
		Remove-Item $OutputFile -Force
		Write-Host "Done!"
	}
else
	{
		Write-Host "Cleanup of last output file not found... Good!"
	}
 
IF ( -NOT ( Get-PSSnapin -Name "Microsoft.Exchange.Management.PowerShell.E2010" -ErrorAction SilentlyContinue )) { Add-PSSnapin "Microsoft.Exchange.Management.PowerShell.E2010" }
 
$UserCredential = Get-Credential "Domain\User"
$saveto = "C:\listmembers.txt"
$UserEntryGroupName = Read-Host "Enter the Group you would like to get the members"
 
Get-DistributionGroup -identity "$UserEntryGroupName" | sort name | ForEach-Object {
		"`r`n$($_.Name)`r`n=============" | Add-Content $saveto
		Get-DistributionGroupMember $_.Name | sort Name | ForEach-Object {
					$_.Name + " <" + $_.PrimarySMTPAddress + ">" | Add-Content $saveto
				}
		}
 
Notepad c:\listmembers.txt

Leave a Reply

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