CAML 查询过滤 where 子句

CAML query filtering where clause

我在 powershell 中有以下 caml。如果我在 CAML 查询中对 $month 进行硬编码,那么它就可以工作。我使用的语法正确吗?

write-host $month
$CAML = '<Where>
         <Eq>
            <FieldRef Name="Period" />
            <Value Type="Text">$month</Value>
         </Eq>
        </Where>'

您的变量没有被替换,因为您使用的是单引号。您可以使用双引号或格式字符串(别名 -f):

write-host $month
$CAML = '<Where>
         <Eq>
            <FieldRef Name="Period" />
            <Value Type="Text">{0}</Value>
         </Eq>
        </Where>' -f $month

在 PowerShell 中,字符串是 可扩展(类似于 perl 中的可插入字符串),或者是 文字

双引号 (") 中的任何内容都是可扩展的,而单引号 (') 用于字符串文字,如您的情况。

$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

对于多行字符串,使用here-string(在其他语言中通常称为here-docs)。适用相同规则:

$CAML = @"
<Where>
  <Eq>
    <FieldRef Name="Period" />
    <Value Type="Text">$month</Value>
  </Eq>
</Where>
"@ 

如果要使用字符串文字(即,如果字符串包含其他特殊字符或要保留的文字 $s)但需要插入特定变量值,请使用 -f 格式运算符 :

$CAML = @'
<Where>
  <Eq>
    <FieldRef Name="Period" />
    <Value Type="Text">{0}</Value>
  </Eq>
</Where>
'@ -f $month

要了解有关字符串扩展和引用的更多信息,请参阅 Get-Help about_Quoting_Rules

谢谢吉萨克。只是想分享以下代码,因为这个也可以。

$CAML = "<Where>
             <Eq>
                <FieldRef Name='Period' />
                <Value Type='Text'>$($month)</Value>
             </Eq>
            </Where>"