1

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.

mklement0
  • 382,024
  • 64
  • 607
  • 775
fishtail
  • 353
  • 3
  • 6

3 Answers3

3

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.

  • NoteThanks, AdminOfThings: Unlike 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.
mklement0
  • 382,024
  • 64
  • 607
  • 775
0

A PowerShell variable inside of single quotes is not expanded, so $dn is not abc.com but $dn, just replace the single quotes with double quotes.

Peter Hahndorf
  • 10,767
  • 4
  • 42
  • 58
  • sorry, but that still gave me an empty return. – fishtail Jan 11 '21 at 18:57
  • The real problem is the use of a script block (`{ ... }`), which binds to the `[string]`-typed `-Filter` parameter by its verbatim (unexpanded) content, irrespective of what that content is. – mklement0 Jan 11 '21 at 19:09
0

What I do is put the wildcards inside a new variable and just use that.

$a = "123"
$b = "*$a*"
Get-<insert command with filter> -filter {name -like $b}

I'm sure there are a million better ways to do this depending on the kind of object you are working with. I'm sure I will get schooled here.

I mainly use this method when I am working within a confined dataset that I am familiar with. e.g. a list of locations