If you have a requirement to create multiple dynamic distribution lists, then you might consider using the Exchange Management Shell to automate the process and save time. However before you try this, there’s some caveats worth knowing before you encounter them.
In the below example, we’ll look to create multiple Dynamic Distribution Groups using input from the CSV file shown below:
Name |
Alias |
EmployeeType |
All Executives |
AllExecutives |
Executive |
All Call Centre Staff |
AllCallCentreStaff |
CallCentre |
All Field Staff |
AllFieldStaff |
FieldStaff |
With most PowerShell cmdlets, we’d expect to be able to Import the CSV, then iterate through each line using the New-DynamicDistributionGroup cmdlet to create the Dynamic Distribution Group, passing the fields from the CSV file directly to the cmdlet.
An example of how you might expect this to be written is shown below:
$DistGroups = Import-CSV .\DistributionGroups.csv foreach ($DG in $DistGroups) { $RecipientFilter = "((RecipientType -eq 'MailUser' -or RecipientType -eq 'Mailcontact') -and (CustomAttribute1 -eq '$($DG.EmployeeType)'))" New-DynamicDistributionGroup -Name $DG.Name -Alias $DG.Alias -RecipientFilter $RecipientFilter }
However, this will not work as expected, as although $DG.Name and $DG.Alias are translated to the current values within the foreach loop, the $DG.EmployeeType value corresponding to the current row in the CSV file won’t be translated, and instead will be left as the variable name – exactly as it’s shown above.
The solution to this is straightforward. We’ll create the recipient filter first before passing it to the New-DynamicDistributionGroup cmdlet, as shown below:
$DistGroups = Import-CSV .\DistributionGroups.csv foreach ($DG in $DistGroups) { New-DynamicDistributionGroup -Name $DG.Name -Alias $DG.Alias -RecipientFilter {((RecipientType -eq 'MailUser' -or RecipientType -eq 'Mailcontact') -and (CustomAttribute1 -eq '$($DG.EmployeeType)'))} }
The new Dynamic Distribution Group will now function as expected.