2016-05-02 80 views
0

我在PowerShell中有以下caml。如果我在CAML查詢中對$月進行硬編碼,那麼它就可以工作。我使用的語法是否正確?CAML查詢過濾where子句

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

回答

2

在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> 
"@ 

如果你想用一個字符串(即如果字符串包含要保留其他特殊字符或文字$秒),但你需要插入一個特定的變量值,使用在-f格式操作as shown by @jisaak

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

要了解更多關於字符串擴張和報價,請參閱Get-Help about_Quoting_Rules

1

您的變量不會被替換,因爲您使用的是單引號。你要麼可以使用雙引號,或者格式字符串(化名-f):

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

感謝您的快速修復。其作品。不過,我剛剛學習下面的代碼也會起作用。 $ CAML =「 \t \t \t \t \t \t \t \t \t \t \t <值類型= '文本'> $($月) \t \t \t \t \t \t「 –

0

謝謝Jissak。只是想分享下面的代碼,因爲這個工程也是如此。

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

在你的情況下,它會工作沒有子表達式運算符('$()')爲好。 –