Reputation: 367
I'm working on this powershell script to deal with exchange mailboxes, and one of the parameters (in a lot of the commands i have to run) needs a variable embedded in it under RecipientFilter. No matter what type of expansion i do, it always evaluates it literally (as $prefix) instead of expanding it. I'm not sure if there's a special way i'm supposed to escape it, or what. Ideas?
$prefix="FAKEDOM"
New-AddressList -name "AL_${prefix}_Contacts" -RecipientFilter {(RecipientType -eq 'MailContact') -and (CustomAttribute15 -eq $prefix)}
Edit: fixed variable name. Note that the question is for the second use of $prefix, the first one is working correctly.
Edit: Working solution:
New-AddressList -name "AL_${prefix}_Contacts" -RecipientFilter "(RecipientType -eq 'MailContact') -and (CustomAttribute15 -eq `"${prefix}`" )"
Upvotes: 3
Views: 5420
Reputation: 5056
Neither $($variableName)
nor ${variableName}
worked for me for variable expansion in parameters with Powershell 4 but the following did:
$prefix="FAKEDOM"
New-AddressList -name ("AL_" + $prefix + "_Contacts") -RecipientFilter {(RecipientType -eq 'MailContact') -and (CustomAttribute15 -eq $prefix)}
Upvotes: 0
Reputation: 16792
Your variable (at least in the sample code) is named $prefix
, not $fakedom
. You need to use the proper variable name in your expansion.
Also note that the underscore char will be assumed to be part of the variable name in the replacement string, so you will need to use either $($variableName)
or ${variableName}
. That is, you can't do a replacement like this: "vanilla_$variableName_strawberry"
, Powershell will look for a variable named variableName_Strawberry"
, which doesn't exist.
All up, this is what you need:
$prefix="FAKEDOM"
New-AddressList -name "AL_${prefix}_Contacts" -RecipientFilter {(RecipientType -eq 'MailContact') -and (CustomAttribute15 -eq $prefix)}
Edit
Your edit makes it clear the first use of $prefix
is fine, and it's the filter that is causing trouble. -RecipientFilter
is a string property, but you are not enclosing your filter expression in any kind of quotes. Instead you use {}
brackets. That's fine in general, but Powershell will not expand variables when your string is specified via {}
brackets.
PS> function Parrot([string] $Message){ $message }
PS> $food = 'cracker'
PS> Parrot {Polly want a $food ?}
Polly want a $food ?
You need to change to using double-quotes:
PS> Parrot "Polly want a $food ?"
Polly want a cracker ?
So your filter should look like below (adding inner single quotes around the $prefix
value):
-RecipientFilter "(RecipientType -eq 'MailContact') -and (CustomAttribute15 -eq '$prefix')"
Upvotes: 5
Reputation: 26434
Try this:
New-AddressList -name "AL_$($prefix)_Contacts" ...
Notice the extra dollar sign I added.
Upvotes: 2