对变量使用“-Filter”和“-Like”

using "-Filter" and "-Like" with a variable

我有一个拉头发的问题(我认为)

代码如下: $dn="abc.com"

Get-Recipient -Filter {EmailAddresses -Like '$dn'} -- 没用
Get-Recipient -Filter {EmailAddresses -Like '*$dn*'} -- 没用
Get-Recipient -Filter {EmailAddresses -Like *'$dn'*} -- 没用
Get-Recipient -Filter {EmailAddresses -Like '*abc.com*'} -- WORKS

如何让它使用变量而不是文字字符串值?

提前致谢。

单引号内的PowerShell变量没有展开,所以$dn不是abc.com而是$dn,只需将单引号换成双引号即可。

使用expandable string(内插字符串,"..."):

Get-Recipient -Filter "EmailAddresses -Like '*$dn*'"

请注意,Get-Recipient's -Filter argument is a string, and that using a script block ({ ... }) 不仅没有必要,而且会导致概念混乱。

实际上,当传递一个脚本块时,它的逐字内容{}除外)被用作字符串值,所以没有 发生变量引用扩展。

  • 注意谢谢,AdminOfThings: Unlike Get-ADUser (see this answer),Get-Recipient可以不能执行它自己的变量解释,所以一个可扩展字符串("...") 如果要在过滤器中使用除 $null$true$false 以外的 PowerShell 变量或表达式,则 总是 需要,然后必须将其转义为 `$null`$true`$false。 否则,使用 引号(逐字字符串,'...'),其中不需要转义(除了将嵌入的 ' 转义为 '') -参见 Recipient filters in Exchange PowerShell commands and string literals in PowerShell