共用方式為


about_Operator_Precedence

簡短描述

以優先順序 清單 PowerShell 運算子。

完整描述

PowerShell 運算符可讓您建構簡單但功能強大的表達式。 本主題會依優先順序列出運算符。 優先順序是 PowerShell 在相同運算式中出現多個運算符時評估運算子的順序。

當運算符具有相等優先順序時,PowerShell 會從左至右評估它們出現在表達式中。 例外狀況是指派運算符、轉換運算子和負運算子 (!-not-bnot) ,從右至左評估。

您可以使用括號之類的機箱來覆寫標準優先順序,並強制PowerShell在未封閉的部分之前評估表達式的封入部分。

在下列清單中,運算符會依評估的順序列出。 相同行或相同群組中的運算符優先順序相同。

[運算子] 資料行會列出運算子。 [參考] 數據行會列出描述運算子的 PowerShell 說明主題。 若要顯示主題,請輸入 get-help <topic-name>

OPERATOR 參考
$() @() () @{} about_Operators
. ?. (成員存取) about_Operators
:: (靜態) about_Operators
[0] ?[0] (索引運算子) about_Operators
[int] (轉換運算子) about_Operators
-split (一元) about_Split
-join (一元) about_Join
, (逗號運算符) about_Operators
++ -- about_Assignment_Operators
! -not about_Logical_Operators
.. (範圍運算子) about_Operators
-f (格式運算子) about_Operators
- (一元/負數) about_Arithmetic_Operators
* / % about_Arithmetic_Operators
+ - about_Arithmetic_Operators

下列運算符群組具有相等優先順序。 區分大小寫且明確區分大小寫的變異優先順序相同。

OPERATOR 參考
-split (二進位) about_Split
-join (二進位) about_Join
-is -isnot -as about_Type_Operators
-eq -ne -gt -ge -lt -le about_Comparison_Operators
-like -notlike about_Comparison_Operators
-match -notmatch about_Comparison_Operators
-in -notIn about_Comparison_Operators
-contains -notContains about_Comparison_Operators
-replace about_Comparison_Operators

此清單會依優先順序繼續執行下列運算子:

OPERATOR 參考
-band -bnot -bor -bxor -shr -shl about_Arithmetic_Operators
-and -or -xor about_Logical_Operators

下列專案不是 true 運算符。 它們是 PowerShell 命令語法的一部分,而不是表達式語法。 指派一律是發生的最後一個動作。

SYNTAX 參考
. (點來源) about_Operators
& (呼叫) about_Operators
? <if-true> : <if-false> (三元運算符) about_Operators
?? (null 聯合運算子) about_Operators
| (管線運算符) about_Operators
> >> 2> 2>> 2>&1 about_Redirection
&& || (管線鏈結運算子) about_Operators
= += -= *= /= %= ??= about_Assignment_Operators

範例

下列兩個命令顯示算術運算元,以及使用括號來強制PowerShell先評估表達式的封閉部分的效果。

PS> 2 + 3 * 4
14

PS> (2 + 3) * 4
20

下列範例會從本機目錄取得唯讀文本檔,並將其儲存在變數中 $read_only

$read_only = Get-ChildItem *.txt | Where-Object {$_.isReadOnly}

它相當於下列範例。

$read_only = ( Get-ChildItem *.txt | Where-Object {$_.isReadOnly} )

因為管線運算符 (|) 的優先順序高於指派運算符 (=) ,所以 Cmdlet 取得的檔案 Get-ChildItem 會先傳送至 Where-Object Cmdlet 以供篩選,然後再指派給 $read_only 變數。

下列範例示範索引運算符的優先順序高於轉換運算符。

此表達式會建立三個字串的陣列。 然後,它會使用值為0的索引運算符來選取陣列中的第一個物件,也就是第一個字串。 最後,它會將選取的物件轉換成字串。 在此情況下,轉換沒有任何作用。

PS> [string]@('Windows','PowerShell','2.0')[0]
Windows

此表達式會使用括弧,強制在索引選取之前發生轉換作業。 因此,整個陣列會轉換成單一) 字串 (。 然後,索引運算符會選取字串陣列中的第一個專案,也就是第一個字元。

PS> ([string]@('Windows','PowerShell','2.0'))[0]
W

在下列範例中 -gt ,因為 (大於) 運算符的優先順序高於 -and 邏輯 AND) 運算子 (,所以表達式的結果為 FALSE。

PS> 2 -gt 4 -and 1
False

它相當於下列表達式。

PS> (2 -gt 4) -and 1
False

如果 -and 運算符的優先順序較高,則答案會是 TRUE。

PS> 2 -gt (4 -and 1)
True

不過,此範例示範管理運算符優先順序的重要準則。 當表達式難以解譯時,請使用括弧來強制評估順序,即使它強制預設運算符優先順序也是如此。 括號可讓您的意圖清楚顯示正在讀取和維護腳本的人員。

另請參閱