共用方式為


about_Operator_Precedence

簡短描述

依優先順序列出 PowerShell 運算子。

詳細描述

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

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

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

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

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

運算子 參考
$() @() () @{} 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

下列運算子群組的優先順序相等。 其區分大小寫且明確區分大小寫的變體的優先順序相同。

運算子 參考
-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

清單會以下列運算子的優先順序繼續在這裡:

運算子 參考
-band -bnot -bor -bxor -shr -shl about_Arithmetic_Operators
-and -or -xor about_Logical_Operators

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

語法 參考
. (dot-source) about_Operators
& (通話) about_Operators
? <if-true> : <if-false> (三元運算子) about_Operators
?? (null-coalese 運算符) 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會在指派$read_only給變數之前傳送至 Where-Object Cmdlet 進行篩選。

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

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

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

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

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

在下列範例中,因為 -gt (大於) 運算子的優先順序高於 -and (logical 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

不過,此範例示範管理運算符優先順序的重要原則。 當表達式難以讓人員解譯時,請使用括弧來強制評估順序,即使它強制預設運算符優先順序也一致。 括弧會向閱讀和維護腳本的人員清楚說明您的意圖。

另請參閱