Reputation: 11251
I have the following caml within powershell. If I hardcode the $month in the CAML Query then it works. Is the syntax I am using proper?
write-host $month
$CAML = '<Where>
<Eq>
<FieldRef Name="Period" />
<Value Type="Text">$month</Value>
</Eq>
</Where>'
Upvotes: 0
Views: 2572
Reputation: 174660
In PowerShell, strings are either expandable (like interpolatable strings in perl), or literal.
Anything enclosed in double-quotes ("
) is expandable, whereas single-quotes ('
) are used for string literals, as in your case.
$month = 'Jan'
"First month is $month" # This will result in: First month is Jan
'First month is $month' # This will result in: First month is $month
For multi-line strings, use a here-string (usually called here-docs in other languages). Same rules apply:
$CAML = @"
<Where>
<Eq>
<FieldRef Name="Period" />
<Value Type="Text">$month</Value>
</Eq>
</Where>
"@
If you want to use a string literal (ie. if the string contains other special characters or literal $
s that you want to preserve) but you need to insert a specific variable value, use the -f
format operator as shown by @jisaak:
$CAML = @'
<Where>
<Eq>
<FieldRef Name="Period" />
<Value Type="Text">{0}</Value>
</Eq>
</Where>
'@ -f $month
To learn more about string expansion and quoting, please see Get-Help about_Quoting_Rules
Upvotes: 2
Reputation: 11251
Thanks Jissak. Just wanted to share following code as this one works too.
$CAML = "<Where>
<Eq>
<FieldRef Name='Period' />
<Value Type='Text'>$($month)</Value>
</Eq>
</Where>"
Upvotes: 0
Reputation: 58971
Your variable don't get replaced because you are using single quotes. You can either, use double quotes, or a format string (alias -f
):
write-host $month
$CAML = '<Where>
<Eq>
<FieldRef Name="Period" />
<Value Type="Text">{0}</Value>
</Eq>
</Where>' -f $month
Upvotes: 1