Exchange 2013 Email Distribution Group With Excluded Addresses
On a few occasions now I’ve been asked to create an Exchange 2013 Distribution Group that is “All users…except for this list of people…”
Ok…probably indicates laziness on the part of the requester not willing to put together a group of existing Distribution Groups, but who am I to argue! So here’s my method, and a rare excuse to use some Python.
Firstly, we need to export all email addresses from the Distribution Group we want to exclude addresses from. In my case, this was our “All Users” group. In Exchange Management Shell, run the following:
$all_users = Get-DynamicDistributionGroup "Your All Users Group"
Get-Recipient -RecipientPreviewFilter $all_users.RecipientFilter -ResultSize Unlimited | select primarysmtpaddress | Out-File $USERPROFILE$\Desktop\all_users_emails.txt
Next, we need a list of all the users/emails we want to exclude. If they’ve already been given to you as a list of emails, great, skip this next bit. If not, you’ll have to do some PowerShell to reference your AD with the info you’ve got. In my case, it was users contained in a particular security group, so this is the command I used:
Get-ADGroupMember -Identity "Excluded Group Name" | get-aduser -Properties mail | select mail | Out-File $USERPROFILE$\Desktop\exluded_users.txt
We now have two text files that we can cross reference to produce the desired list of emails. Below is a short Python script I wrote for doing that:
# Get all emails from previously exported 'All Users' and put them in an array all_emails = [] all_emails_file = open(r"c:\users\xxxxxx\Desktop\all_users_emails.txt", encoding='utf-16') for line in all_emails_file: # Filter out any blank entries if '@' in line: # Add the email to the array, removing the whitespace all_emails.append(line.split()) # Get all emails from the excluded list and put them in an array unwanted_emails = [] unwanted_emails_file = open(r"c:\users\xxxxxx\Desktop\excluded_users.txt", encoding='utf-16') for line in unwanted_emails_file: # Filter out any blank entries if '@' in line: unwanted_emails.append(line.split()) # Compare the two arrays, only keep emails of people that we haven't sent mails to. Put them in a new array final_mails = [] for wanted_address in all_emails: if wanted_address not in unwanted_emails: final_mails.append(wanted_address) # Output list of emails for Powershell processing with open("output_for_powershell.txt", "w") as txt_file: for line in final_mails: txt_file.write(" ".join(line) + "\n")
Finally, we take the output from the Python script and use PowerShell to add all addresses to a new Distribution Group:
$desired_users = Get-Content $USERPROFILE$\Desktop\output_for_powershell.txt
foreach($email in $desired_users) {Add-DistributionGroupMember -Identity "Name of new Distribution Group" -Member $email}