I've got a hair pulling problem (I think)
Here's the code: $dn="abc.com"
Get-Recipient -Filter {EmailAddresses -Like '$dn'} -- didn't work
Get-Recipient -Filter {EmailAddresses -Like '*$dn*'} -- didn't work
Get-Recipient -Filter {EmailAddresses -Like *'$dn'*} -- didn't work
Get-Recipient -Filter {EmailAddresses -Like '*abc.com*'} -- WORKS
How can I make it work with a variable, instead of a literal string value?
Thanks in advance.
Use an expandable string (interpolating string, "..."
):
Get-Recipient -Filter "EmailAddresses -Like '*$dn*'"
Note that Get-Recipient
's -Filter
argument is a string, and that using a script block ({ ... }
) is not only unnecessary, but leads to conceptual confusion.
In fact, when a script block is passed, its verbatim content (except {
and }
) is used as the string value, so no expansion of variable references takes place.
Get-ADUser
(see this answer), Get-Recipient
can not perform variable interpretation of its own, so an expandable string ("..."
) is always needed if PowerShell variables or expressions other than $null
, $true
and $false
are to be used in a filter, which must then be escaped as `$null
, `$true
and `$false
.
Otherwise, use single-quoting (verbatim strings, '...'
), where no escaping (other than escaping embedded '
as ''
) is needed - see Recipient filters in Exchange PowerShell commands and string literals in PowerShell.