Using filters against objects containing special characters

Another one in the series “blog this so I don’t forget it later”. Here’s the issue: when using server-side filtering (the -Filter parameter, or -RecipientFilter, etc), you have to use the OPATH format and mind some special characters. For example, having an apostrophe in the name of the object.

I run into this when preparing a report on DG membership for some users in specific country. Now, you are probably aware of the quick and easy way to get the “MemberOf” equivalent in EO:

 

Get-Recipient -Filter {Members -eq 'CN=user,OU=tenant.onmicrosoft.com,OU=Microsoft Exchange Hosted Organizations,DC=EURPR03A001,DC=prod,DC=outlook,DC=com'}

 

This lovely one-liner will save you the trouble of having to enumerate all groups and cycle over them! So it greatly reduces the complexity and time of execution for the script. Note the DN handling however – it needs to be enclosed in single quotation marks. Which coincidentally, are used interchangeably with apostrophes. So in effect, every DN that contains an apostrophe (which is totally legit btw), will cause the nice one-liner above to break. The solution – ‘escape’ the apostrophe in the DN by replacing it with… four (yes, that’s f-o-u-r, 4!) other apostrophes. Or in script form:

$dn = (Get-Mailbox user).DistinguishedName
$dnnew = “'” + “$($dn.Replace(“'”,”''''”))” + “'”
$cmd = “Get-Recipient -Filter 'Members -eq '$dnnew''”
$list = Invoke-Expression $cmd

Now, the filter should work just fine!

This entry was posted in Exchange Online, Office 365, PowerShell. Bookmark the permalink.

Leave a Reply

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