DynamicDistributionGroup for all users in a particular storage group

Lots of people are asking lots of questions at the ExchangeNinjas wiki! Glad to see so much participation both from within the Exchange team and also from the broad Exchange community!!

This question struck me as pretty interesting, so I figured I'd surface it on the blog as well as answering it (a few weeks ago) on the wiki... From the wiki's Recipient Management FAQs page (originally was posted to the Ask a Question page) :

Q: I want to create a custom dynamic distribution group for all users in a storage group. I can get the user if I use: get-mailbox | where {$_.Database -like "*<SGName>*"}
BUT this doesn't work for a new DDG :
new-DynamicDistributionGroup -alias test1a -name test1a -recipientfilter {Database -like "*SG01-SUKMSDMBX03*"} -org exchorg.local

I get no members! It will work on a per server basis, but this it no good for me. Can you help? Is this possible?

A: The problem is that the "Database" filter can't do partial string matches, because underneath this property is actually a distinguished name value in the AD (which can't do substring matching). Building an infrastructure that allows you to direct email to mailboxes on a storage group is definitely possible -- just not like this. Instead, you need to ensure you're using the full distinguished name for each database you want to compare against, and not using wildcards (ie, asterisk *)

There's an easy way to do this and a hard way. The hard way I'll just talk about, then I'll show you the easy way. The hard way would be to iterate through all of the MDBs in your selected storage group, concatenating a filter-parser string made up of their DNs... with appropriately placed "-or" operators between. Then pass this string into the New-DDG cmdlet as the RecipientFilter. Yuck.

The easy way is to create a DDG for each mailboxdatabase. Then create a DistributionGroup (doesn't have to be DDG) and add all of these per-MDB DDGs into the DG. Here's how that might look:

new-distributiongroup DG-MySg1 -Type Distribution -SamAccountName DG-MySg1
get-mailboxdatabase -Server Srv1 -StorageGroup MySG1 | % { New-DynamicDistributionGroup "DDG-$($_.Name)" -RecipientFilter "Database -eq '$($_.Identity.DistinguishedName)'" } | % { Add-DistributionGroupMember DG-MySg1 -Member $_.Identity }

Updated July10: Added -Server switch to make it a more real-world syntax.