要在尝试时创建内联过滤器,您需要使用子表达式运算符$()。这将允许 PowerShell 在将其传递给-Filter 参数之前处理内部的所有内容。
Get-ADUser -Filter "EmailAddress -eq '$($userobject.GivenName + '.' + $userobject.SurName + '@overflow.com')'"
最终,一旦 PowerShell 执行其变量扩展和字符串插值,过滤器预期为 Property -operator 'Value' 或 Property -operator "Value"。达到这种状态的方式可能会有所不同。
正如Tomalak's answer 提到的,-Filter 参数接受字符串值而不是脚本块。为什么命令创建者将 ({}) 列为文档中的首选语法是一个谜。由于它接受一个字符串并且您很少希望字符串中的内容是文字,因此最好用双引号将过滤器括起来。然后在里面使用单引号。有时,复杂的过滤器会混合使用单引号和双引号,但您只需要注意一个开头引号会发现无意的结尾引号。甚至需要多组引号的原因是因为-Filter 包含比较运算符,这些运算符期望这些运算符的右侧被引用。如果您不混合引用类型,则必须想出更多创造性的方法来绕过插值。有关此行为的一些示例,请参见下文。请注意,Double Quotes outside while Escaping... 和 Double Quotes Outside 和 Single Quotes Inside 场景使-Filter 收到它想要的内容。字符串外的单引号将不允许变量扩展($str 将只是字面上的 $str)。
双引号:
PS> "string with double quotes"
string with double quotes
单引号:
PS> 'single quotes'
single quotes
外加双引号,内加单引号:
PS> "outside doubles 'inside singles'"
outside doubles 'inside singles'
内外双引号:
PS> "double "double quotes""
At line:1 char:10
+ "double "double quotes""
+ ~~~~~~
Unexpected token 'double' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : UnexpectedToken
With all that said, it is just more readable to do your string building outside of the filter first.
外加单引号,内加双引号:
PS> 'outside singles "inside doubles"'
outside singles "inside doubles"
外部双引号,内部单引号变量:
PS> $str = "variable string"
PS> "outside doubles single variable '$str'"
outside doubles single variable 'variable string'
单引号外,内双引号变量:
PS> 'outside singles double variable "$str"'
outside singles double variable "$str"
外部双引号,内部转义双引号:
PS> "fancy escaping with variable ""$str"""
fancy escaping with variable "variable string"
PS> "fancy escaping with variable `"$str`""
fancy escaping with variable "variable string"