Powershell参数变量扩展

时间:2012-10-26 01:38:26

标签: powershell exchange-server

我正在研究这个PowerShell脚本来处理交换邮箱,其中一个参数(在我必须运行的很多命令中)需要在RecipientFilter下嵌入一个变量。无论我做什么类型的扩展,它总是按字面意思(作为$前缀)进行评估,而不是扩展它。我不确定是否有一种特殊的方式我应该逃避它,或者是什么。想法?

$prefix="FAKEDOM"

New-AddressList -name "AL_${prefix}_Contacts" -RecipientFilter {(RecipientType -eq 'MailContact') -and (CustomAttribute15 -eq $prefix)}

编辑:固定变量名称。请注意,问题是第二次使用$ prefix,第一次使用正确。

编辑:工作解决方案:

 New-AddressList -name "AL_${prefix}_Contacts" -RecipientFilter "(RecipientType -eq 'MailContact') -and (CustomAttribute15 -eq `"${prefix}`" )"

3 个答案:

答案 0 :(得分:5)

您的变量(至少在示例代码中)名为$prefix,而不是$fakedom。您需要在扩展中使用正确的变量名称。

另请注意,下划线字符将被假定为替换字符串中变量名称的一部分,因此您需要使用$($variableName)${variableName}。也就是说,你不能做这样的替换:"vanilla_$variableName_strawberry",Powershell会查找一个名为variableName_Strawberry"的变量,它不存在。

总而言之,这就是你所需要的:

$prefix="FAKEDOM"

New-AddressList -name "AL_${prefix}_Contacts" -RecipientFilter {(RecipientType -eq 'MailContact') -and (CustomAttribute15 -eq $prefix)}

修改

您的编辑清楚地表明首次使用$prefix很好,而且它是导致问题的过滤器。 -RecipientFilter字符串属性,但您没有将过滤器表达式括在任何类型的引号中。而是使用{}括号。一般来说这很好,但是当你的字符串通过{}括号指定时,Powershell不会扩展变量。

PS> function Parrot([string] $Message){ $message }
PS> $food = 'cracker'
PS> Parrot {Polly want a $food ?}
Polly want a $food ?

您需要更改为使用双引号:

PS> Parrot "Polly want a $food ?"
Polly want a cracker ?

因此,您的过滤器应如下所示(在$prefix值附近添加内部单引号):

-RecipientFilter "(RecipientType -eq 'MailContact') -and (CustomAttribute15 -eq '$prefix')"

答案 1 :(得分:2)

试试这个:

New-AddressList -name "AL_$($prefix)_Contacts" ...

请注意我添加的额外美元符号。

答案 2 :(得分:0)

对于我来说,$($variableName)${variableName}都没有为Powershell 4参数的变量扩展工作,但以下是:

$prefix="FAKEDOM"

New-AddressList -name ("AL_" + $prefix + "_Contacts") -RecipientFilter {(RecipientType -eq 'MailContact') -and (CustomAttribute15 -eq $prefix)}