about_Arithmetic_Operators

適用於: Windows PowerShell 2.0, Windows PowerShell 3.0, Windows PowerShell 4.0, Windows PowerShell 5.0

在此插入簡介。

主題

about_Arithmetic_Operators

簡短描述

描述在 Windows PowerShell® 中執行算術的運算子。

詳細描述

算術運算子會計算數值。您可以使用一或多個算術運算子對數值加、減、乘、除,以及計算除法運算的餘數 (模數)。

此外,加法運算子 (+) 和乘法運算子 (*) 也能在字串、陣列和雜湊表上運算。加法運算子可串連輸入。乘法運算子會傳回該輸入的多個複本。您更可以混合算術陳述式中的物件類型。用來評估陳述式的方法取決於運算式中最左邊的物件類型。

從 Windows PowerShell 2.0 開始,所有算術運算子都能處理 64 位元數字。

從 Windows PowerShell 3.0 開始,-shr (右移) 和 -shl (左移) 也已加入,藉此支援 Windows PowerShell 中的位元算術。

Windows PowerShell 支援下列的算術運算子:

Operator  Description                             Example
--------  -----------                             -------
+         Adds integers; concatenates strings,    6+2
          arrays, and hash tables.                "file" + "name"
-        Subtracts one value from another        6-2
          value.                                  (get-date).date - 1
-        Makes a number a negative number.       -6+2
                                                  -4
*         Multiplies integers; copies strings     6*2
          and arrays the specified number of      "w" * 3
          times.
/         Divides two values.                     6/2
%         Returns the remainder of a division     7%2
          operation.
-shl      Shift-left                              100 -shl 2
-shr      Shift-right                             100 -shr 1

運算子優先順序

Windows PowerShell 以下列順序處理算術運算子:

        Parentheses ()
        - (for a negative number)
        *, /, %
        +, - (for subtraction)

Windows PowerShell 根據優先順序規則從左到右處理運算式。下列範例顯示優先順序規則的作用:

C:\PS> 3+6/3*4 
        11

C:\PS> 10+4/2
        12

C:\PS> (10+4)/2
        7

C:\PS> (3+3)/ (1+1)
        3

Windows PowerShell 評估運算式的順序可能會與您曾使用過之其他程式設計和指令碼語言不同。下列範例顯示複雜的指派陳述式。

C:\PS> $a = 0
        C:\PS> $b = 1,2
        C:\PS> $c = -1,-2
        
        C:\PS> $b[$a] = $c[$a++]
        
        C:\PS> $b
        1
        -1

在此範例中,運算式 $a++ 會在 $c[$a++] 之前評估。評估 $a++ 會變更 $a 的值。在 $b[$a] 的變數 $a 等於 1 而非 0,所以該陳述式會指派值給 $b[1],而非 $b[0]。

除法和進位

當除法運算的商數是整數時,Windows PowerShell 會將該值四捨五入至最接近的整數。當該值為 .5 時,它會四捨五入到最接近的雙數。

下列範例顯示進位至最接近雙數的作用。

C:\PS> [int]( 5 / 2 )
        2

C:\PS> [int]( 7 / 2 )
        4

非數值類型的加法和乘法

您可以將數字、字串、陣列和雜湊表相加。而且,您可以將數字、字串和陣列相乘。不過,您不能將雜湊表相乘。

當您將將字串、陣列或雜湊表相加時,便會串連這些項目。當您串連集合時,例如陣列或雜湊表,便會建立一個新物件,其中包含兩個集合的物件。如果您嘗試串連具有相同索引鍵的雜湊表,作業便會失敗。

例如,下列命令會建立兩個陣列,然後對其相加:

C:\PS> $a = 1,2,3
C:\PS> $b = "A","B","C"
C:\PS> $a + $b
1
2
3
A
B
C

您也可以執行不同類型物件上的算術運算。Windows PowerShell 執行的作業會由該作業中最左邊物件的 Microsoft .NET Framework 類型決定。Windows PowerShell 會嘗試將該作業中的所有物件轉換為第一個物件的 .NET Framework 類型。如果成功地轉換了物件,它就會執行適用於第一個物件之 .NET Framework 類型的作業。如果它無法轉換任何物件,則此作業會失敗。

下列範例示範在包含不同物件類型的作業中使用加法和乘法運算子:

C:\PS> "file" + 16
        file16

C:\PS> $array = 1,2,3
        C:\PS> $array + 16
        1
        2
        3
        16

C:\PS> $array + "file"
        1
        2
        3
        file

C:\PS> "file" * 3
        filefilefile

因為用來評估陳述式的方法由最左邊的物件決定,所以 Windows PowerShell 中的加法和乘法並不是嚴格可交換的。例如 (a + b) 不一定等於 (b + a),而且 (a * b) 也不一定等於 (b * a)。

下列範例會示範這個原則:

C:\PS> "file" + 2
        file2

C:\PS> 2 + "file"
        Cannot convert value "file" to type "System.Int32". Error: "Input
        string was not in a correct format."
        At line:1 char:4
        + 2 + <<<<  "file"

C:\PS> "file" * 3
        filefilefile

C:\PS> 3 * "file"
        Cannot convert value "file" to type "System.Int32". Error: "Input 
        string was not in a correct format."
        At line:1 char:4
        + 3 * <<<<  "file"

雜湊表則是稍有不同的案例。您可以加入雜湊表。而且您可以將雜湊表加入陣列中。不過,您無法將任何其他類型加入雜湊表。

下列範例示範如何將雜湊表彼此相加以及加入其他物件:

C:\PS> $hash1 = @{a=1; b=2; c=3}
        C:\PS> $hash2 = @{c1="Server01"; c2="Server02"}
        C:\PS> $hash1 + $hash2
        Name                           Value
        ----                           -----
        c2                             Server02
        a                              1
        b                              2
        c1                             Server01
        c                              3
C:\PS> $hash1 + 2
You can add another hash table only to a hash table.
At line:1 char:9
+ $hash1 + <<<<  2

C:\PS> 2 + $hash1
Cannot convert "System.Collections.Hashtable" to "System.Int32".
At line:1 char:4
+ 2 + <<<<  $hash1

下列範例示範您可以將雜湊表加入陣列。會將整個雜湊表當做單一物件加入陣列。

C:\PS> $array = 1,2,3
C:\PS> $array + $hash1
1
2
3
        Name                           Value
        ----                           -----
        a                              1
        b                              2
        c                              3
C:\PS> $sum = $array + $hash1
C:\PS> $sum.count
4

C:\PS> $sum[3]
Name                           Value
----                           -----
a                              1
b                              2
c                              3

PS C:\ps-test> $sum + $hash2
1
2
3

Name                           Value
----                           -----
a                              1
b                              2
c                              3
c2                             Server02

下列範例會顯示您無法加入包含相同索引鍵的雜湊表:

C:\PS> $hash1 = @{a=1; b=2; c=3}
C:\PS> $hash2 = @{c="red"}
C:\PS> $hash1 + $hash2
Bad argument to operator '+': Item has already been added. 
Key in dictionary: 'c'    Key being added: 'c'.
At line:1 char:9
+ $hash1 + <<<<  $hash2

雖然加法運算子很實用,但請使用指派運算子,將元素加入雜湊表與陣列。如需詳細資訊,請參閱 about_assignment_operators。下列範例會使用 += 指派運算子將項目加入陣列:

C:\PS>  $array
1
2
3

C:\PS>  $array + "file"
1
2
3
file

C:\PS>  $array
1
2
3

C:\PS>  $array += "file"
C:\PS>  $array
1
2
3
file

C:\PS> $hash1

Name                           Value
----                           -----
a                              1
b                              2
c                              3

C:\PS> $hash1 += @{e = 5}
C:\PS> $hash1

Name                           Value
----                           -----
a                              1
b                              2
e                              5
c                              3

Windows PowerShell 會自動選取最能展現結果而不會遺失有效位數的 .NET Framework 數字類型。例如:

C:\PS> 2 + 3.1
5.1
C:\PS> (2). GetType().FullName
System.Int32
C:\PS> (2 + 3.1).GetType().FullName
System.Double

如果作業結果對該類型而言太大,則會將此結果類型擴展以容納結果,如下列範例所示:

C:\PS> (512MB).GetType().FullName
System.Int32
C:\PS> (512MB * 512MB).GetType().FullName
System.Double

結果類型不一定會與其中一個運算元相同。在下列範例中,負數的值無法轉換為帶正負號的整數,且該不帶正負號的整數太大而無法轉換成 Int32:

C:\PS> ([int32]::minvalue + [uint32]::maxvalue).gettype().fullname
System.Int64

在此範例中,Int64 可以容納這兩種類型。

System.Decimal 類型為例外狀況。如果任一運算元具有 Decimal 類型,結果就會是 Decimal 類型。如果結果對 Decimal 類型太大,就不會轉換成雙精確度浮點數,而是會產生錯誤。

C:\PS> [Decimal]::maxvalue
79228162514264337593543950335
C:\PS> [Decimal]::maxvalue + 1
Value was either too large or too small for a Decimal.
At line:1 char:22
+ [Decimal]::maxvalue + <<<<  1

算術運算子和變數

您也可以搭配變數使用算術運算子。運算子會在變數值上作用。下列範例示範如何搭配變數使用算術運算子:

C:\PS> $intA = 6 
C:\PS> $intB = 4 
C:\PS> $intA + $intB 

10 

C:\PS> $a = "Windows " 
C:\PS> $b = "PowerShell " 
C:\PS> $c = 2 
C:\PS> $a + $b + $c

Windows PowerShell 2

算術運算子和命令

通常您可在數字、字串和陣列的運算式中使用算術運算子。不過,您也可以搭配命令傳回的物件及搭配該物件的屬性,使用算術運算子。

下列範例示範如何使用 Windows PowerShell 命令在運算式中使用算術運算子:

C:\PS> get-date
Wednesday, January 02, 2008 1:28:42 PM

C:\PS> $day = new-timespan -day 1
C:\PS> get-date + $day
Thursday, January 03, 2008 1:34:52 PM

C:\PS> get-process | where {($_.ws * 2) -gt 50mb}
Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
   1896      39    50968      30620   264 1,572.55   1104 explorer
  12802      78   188468      81032   753 3,676.39   5676 OUTLOOK
    660       9    36168      26956   143    12.20    988 PowerShell
    561      14     6592      28144   110 1,010.09    496 services
   3476      80    34664      26092   234 ...45.69    876 svchost
    967      30    58804      59496   416   930.97   2508 WINWORD

範例

下列範例示範如何使用 Windows PowerShell 中的算術運算子:

C:\PS> 1 + 1
2

C:\PS> 1 - 1 
0

C:\PS> -(6 + 3) 
-9

C:\PS> 6 * 2 
12

C:\PS> 7 / 2 
3.5 

C:\PS> 7 % 2 
1 

C:\PS> w * 3 
www 

C:\PS> 3 * "w" 
Cannot convert value "w" to type "System.Int32". Error: "Input string was not in a correct format." 
At line:1 char:4 
+ 3 * <<<< "w" 

PS C:\ps-test> "Windows" + " " + "PowerShell" 
Windows PowerShell

PS C:\ps-test> $a = "Windows" + " " + "PowerShell" 
PS C:\ps-test> $a 
Windows PowerShell

C:\PS> $a[0] 
W

C:\PS> $a = "TestFiles.txt" 
C:\PS> $b = "C:\Logs\" 
C:\PS> $b + $a 
C:\Logs\TestFiles.txt

C:\PS> $a = 1,2,3 
C:\PS> $a + 4 
1 
2 
3 
4

C:\PS> $servers = @{0 = "LocalHost"; 1 = "Server01"; 2 = "Server02"} 
C:\PS> $servers + @{3 = "Server03"} 
Name Value 
---- ----- 
3 Server03 
2 Server02 
1 Server01 
0 LocalHost 

C:\PS> $servers 
Name Value 
---- ----- 
2 Server02 
1 Server01 
0 LocalHost

C:\PS> $servers += @{3 = "Server03"} #Use assignment operator 
C:\PS> $servers 
Name Value 
---- ----- 
3 Server03 
2 Server02 
1 Server01 
0 LocalHost

在 WINDOWS POWERSHELL 中的位元算術

Windows PowerShell 支援位元算術的 -shl (左移) 和 -shr (右移) 運算子。

在 Windows PowerShell 3.0 中引進了這些運算子。

在位元左移位運算中,所有位元會往左移 "n" 個位數,其中 "n" 是右運算元的值。會將一個零插入個位數的位置。

當左運算元是整數 (32 位元) 值時,右運算元較低的 5 個位元會決定左運算元要移位多少位元。

當左運算元是長數值 (64 位元) 時,右運算元較低的 6 個位元會決定左運算元要移位多少位元。

PS C:\> 21 -shl 1
42

00010101  (21)
00101010  (42)

PS C:\> 21 -shl 2
84

00010101  (21)
00101010  (42)
01010100  (84)

在位元右移運算中,所有位元會往右移 "n" 個位數,其中 "n" 是由右運算元所指定。當正值或不帶正負號的值右移時,右移運算子 (-shr) 會在最左邊的位置插入一個零。

當左運算元是整數 (32 位元) 值時,右運算元較低的 5 個位元會決定左運算元要移位多少位元。

當左運算元是長數值 (64 位元) 時,右運算元較低的 6 個位元會決定左運算元要移位多少位元。

PS C:\> 21 -shr 1
10

00010101  (21)
00001010  (10)

PS C:\> 21 -shr 2
5

00010101  (21)
00001010  (10)
00000101  ( 5)

另請參閱

about_arrays

about_assignment_operators

about_comparison_operators

about_hash_tables

about_operators

about_variables

Get-Date

Get-Date

New-TimeSpan