Exchange 2007 Add To Distribution Group From Text File

Another interesting request came my way. Since I work in a school district we have a decent amount of “turnover” or whatever you may want to call it every year and at random times throughout the year. This isn’t necessarily folks leaving the district but maybe moving from one grade level to another or taking leave and having a long term substitute take their place. So the request was to have these distribution groups which are populated with a listing of teachers per grade level, generated from our student information system. Naturally the information system doesn’t provide a way to update Exchange and is not at all AD integrated. So what I did was request an export of teachers by grade level (one text file per grade level) and their (thankfully aligned with AD) username. I then placed those text files in a folder, created the distribution groups and ran the below script.

First use powershell to create a distribution group:

# Create a new distribution group and mail-enable it (source)

new-DistributionGroup -alias testDistGroup -name “Test Distribution Group” -type distribution -org “domain.local/OU/OU” -SamAccountName Testers

Next create a .ps1 file with the following:

# Import the usernames from text file

$Import=Get-Content “.\file.txt”

# clear the distribution group to remove all members. This saved me building in a lot of comparison logic

# compared to the small group sizes I was dealing with for updates to the list. In a massive environment you’ll want to update not rip and replace

get-distributiongroupmember -identity “domain.local/OU/OU/DistributionGroup” | remove-distributiongroupmember “domain.local/OU/OU/DistributionGroup” -Confirm:$false

#For every line in the import file:

foreach ($user in $Import) {

#get the user’s PrimarySMTPAddress and copy it to a string

$userAddress = (get-mailbox $($user)).PrimarySmtpAddress.ToString()

#For formatting purposes and to get some output from the script

echo ********* Adding $username

add-distributiongroupmember -identity “domain.local/OU/OU/DistributionGroup” -member $userAddress


echo *** SCRIPT COMPLETE ***

Your input file simply needs a list of usernames, one per line like this:




user 10

That’s all there is to it.

Oh and if you want to see the contents of your distribution group:
PS >$foo = Get-DynamicDistributionGroup -Identity “groupname”

PS > Get-Recipient -resultsize unlimited -RecipientPreviewFilter $foo.RecipientFilter | more