• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
OpenTechTips

OpenTechTips

Comprehensive IT Guides for Pros and Enthusiasts

MENUMENU
  • HOME
  • ALL TOPICS
    • Exchange
    • InfoSec
    • Linux
    • Networking
    • Scripting
      • PowerShell
    • SSL
    • Tools
    • Virtualization
    • Web
    • Windows
  • ABOUT
  • SUBSCRIBE
Home » PowerShell script for mass-creating Distribution Groups

PowerShell script for mass-creating Distribution Groups

May 5, 2020 - by Zsolt Agoston - last edited on May 5, 2020

Do you want to automate distribution group creation, making your job easier? With this script you'll be able to mass-create distribution groups. It takes a simple text file as an input that contains a list of delivery group names, and members. The input list should look like this:

New Group Name
First Member
Second Member

Second Group Name

First Member
Second Member
Third Member
...

The blocks are separated with one or more new lines. Then the script check if the users exist or are unique in the system. If not, a detailed warning is thrown back.

PowerShell script for mass-creating Distribution Groups

The function takes multiple arguments like the input file (if not specified it's dg.txt), also logging can be enabled. By default, the script runs dry, to actually create the groups use the -Commit switch!

DG-create -List dg.txt -ExternalAccepted:$true -Commit

PowerShell script for mass-creating Distribution Groups

The Script

# Script to create delivery groups from file that consists of blocks devided by one or more empty lines.
# The first entry of each block is the name of the delivery group, the subsequent entries are members with fullaccess-
# and SendOnBehalf rights over it. The name can contain spaces, that case the script will replace them with a "."
#
# Example: DG-create -List requested.txt -Ticket WO000007684957 -Logging -Commit
#
# Parameters:
#	-List [file]: the location of the list file. If not defined, dg.txt by default
#	-Logging: if used, logging will be enabled and a log file is created in the current location
#				logfile name: DG-Create_yyy_MM_dd_HH_mm_ss.log
#	-ExternalAccepted: if used, external emails will be allowed. Default is InternalOnly
#	-Ticket: the WO number if exist
#	-Commit:	use the switch to commit changes, otherwise a dry-run is performed
#
#
# Example:
# 
# New Group Name
# First Member
# Second Member
#
# Second Group Name
# First Member
# Second Member
# ...
#
# Procedure:
# 1. the script is checking if the members exist and are unique
# 2. creating DG
# 4. adding members to the groups

function DG-create {
param ($List, $Ticket, [switch]$Logging, [switch]$ExternalAccepted, [switch]$Commit)

# Set logfile and the logging function, we use WriteLog to replace Write-Host in the rest of the script
$logfile = "DG-Create_$((get-date).tostring("yyy_MM_dd_HH_mm_ss")).log"
function WriteLog ($disp, $dispattr){
	if (!($dispattr)) {$dispattr = "white"}
	write-host -f $dispattr $disp
	if ($Logging) {add-content $logfile -value $disp}
}

# Set and check if the list file exists
if ($List -eq $null) {$listfile = "dg.txt"} else { $listfile = $List }
if (!(Test-Path $listfile)) {
	write-host -n -f magenta "The list file does not exist: "
	write-host -f yellow "$listfile"
	break
}
# Get default domain
$DefaultDomain = (Get-AcceptedDomain | ?{$_.default -eq $true}).domainname

# Declare counters and array
$i = $e = $dtaken = 0
$all = @{}

# Building hash table with group - member association
get-content $listfile | %{

	if ($_ -like ""){ $i = 0 } else {
		if ($i -eq 0){
			$i++
			$dg = $_.trim().replace(" ",".")
			if ( !$all.$dg ) { $all.$dg = @() }
			} else { $all.$dg += $_.trim() }

		}
	}

# Check and confirm groups and members
foreach ($dg in $all.Keys) {
	# Check if the delivery group SMTP is already used
	if ((get-recipient "$dg@$DefaultDomain" -ErrorAction Silent) -eq $null) { write-host -f yellow "`r`nName: $($dg.replace("."," "))`r`nSMTP: $dg@$DefaultDomain" } else {
			write-host -f magenta "`r`nName: $dg`r`nSMTP: $dg@$DefaultDomain`t<== already used!!!"
			$dtaken++
	}

	$all.$dg | %{
		# Check if member exists or is unique. If unique, their alias names are displayed on the screen
		if ( (($mb = get-mailbox $($_).trim() -erroraction silent )| measure).count -eq 1) { write-host -f gray "`t$($_) --> $($mb.alias)" } else { $e++; write-host -f magenta "`t$($_) --> does not exist or not unique !!!"}
	}
}

# Display error check results
if ($dtaken -ne 0) {
	write-host -f magenta "`r`nOne or more gelivery group address is already being used, please see above!"
	break}
	
if ($e -ne 0) {
	write-host -f magenta "`r`nThere are non-existent members or members with the wrong name in the list, please correct the list before continuing. You can use alias names in the list!"
	break}

if (!($Commit)) {
	write-host -f green "`r`nIf the above looks OK, please use the -Commit switch to proceed with the changes."
	break

}

#Create DGs
foreach ($dg in $all.Keys) {
	$dg = $dg.trim()
	$dgDisplayed = $dg.replace("."," ")
	
	add-content $logfile -value "Time: $(get-date)"
	WriteLog "`r`nCreating: $dg ..." "green"
	New-DistributionGroup -Name $dgDisplayed -DisplayName $dgDisplayed -Alias $dg -PrimarySmtpAddress "$dg@$DefaultDomain" -RequireSenderAuthenticationEnabled $(!($ExternalAccepted)) -OrganizationalUnit "CN=Users,DC=AlwaysHotCafe,DC=com" | out-null
	Get-ADGroup -Filter {name -like "$dg"} | Set-ADGroup -Description "$Ticket"
	
	add-content $logfile -value "*****"
	WriteLog "Adding members:" "yellow"
	$all.$dg | %{
		$dgmember = $_.trim()
		Add-DistributionGroupMember $dg -Member $dgmember | out-null
		WriteLog "`t`t$dgmember" "gray"
	}
	add-content $logfile -value "*****`r`n*****"
}
}

Reader Interactions

Comments Cancel reply

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

Primary Sidebar

Tools

Secondary Sidebar

  • Terms of Use
  • Disclaimer
  • Privacy Policy
Manage your privacy

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Statistics

Marketing

Features
Always active

Always active
Manage options Manage services Manage {vendor_count} vendors Read more about these purposes
Manage options
{title} {title} {title}
Manage your privacy
To provide the best experiences, we use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Statistics

Marketing

Features
Always active

Always active
Manage options Manage services Manage {vendor_count} vendors Read more about these purposes
Manage options
{title} {title} {title}