关于算术运算符About Arithmetic Operators

简短说明SHORT DESCRIPTION

描述在 PowerShell 中执行算术的运算符。Describes the operators that perform arithmetic in PowerShell.

详细说明LONG DESCRIPTION

算术运算符计算数字值。Arithmetic operators calculate numeric values. 您可以使用一个或多个算术运算符对值进行加法、减、乘和除运算,计算除法运算的余数 (模数) 。You can use one or more arithmetic operators to add, subtract, multiply, and divide values, and to calculate the remainder (modulus) of a division operation.

此外,加法运算符 (+) 和乘法运算符 (*) 也操作字符串、数组和哈希表。In addition, the addition operator (+) and multiplication operator (*) also operate on strings, arrays, and hash tables. 加法运算符用于连接输入。The addition operator concatenates the input. 乘法运算符返回输入的多个副本。The multiplication operator returns multiple copies of the input. 甚至可以在算术语句中混合使用对象类型。You can even mix object types in an arithmetic statement. 用于计算语句的方法由表达式中最左侧的对象的类型确定。The method that is used to evaluate the statement is determined by the type of the leftmost object in the expression.

从 PowerShell 2.0 开始,所有算术运算符都适用于64位数字。Beginning in PowerShell 2.0, all arithmetic operators work on 64-bit numbers.

从 PowerShell 3.0 开始, -shr 添加了 (向右) 和 -shl (向左) ,以便在 PowerShell 中支持按位算法。Beginning in PowerShell 3.0, the -shr (shift-right) and -shl (shift-left) are added to support bitwise arithmetic in PowerShell.

PowerShell 支持以下算术运算符:PowerShell supports the following arithmetic operators:

运算符Operator 说明Description 示例Example
+ 添加整数;各个Adds integers; concatenates 6 + 2
字符串、数组和哈希表。strings, arrays, and hash tables. "file" + "name"
@(1, "one") + @(2.0, "two")
@{"one" = 1} + @{"two" = 2}
- 从一个值中减去另一个值Subtracts one value from another 6 - 2
valuevalue
- 使数字成为负数Makes a number a negative number -6
(Get-Date).AddDays(-1)
* 数字或复制字符串相乘Multiply numbers or copy strings 6 * 2
和数组指定的数字and arrays the specified number @("!") * 4
次。of times. "!" * 3
/ 两个值相除。Divides two values. 6 / 2
% 取模-返回剩余的Modulus - returns the remainder of 7 % 2
除法运算。a division operation.
-带-band 位与Bitwise AND 5 -band 3
-bnot-bnot 按位“非”Bitwise NOT -bnot 5
-bor-bor 按位“或”Bitwise OR 5 -bor 0x03
-bxor-bxor 按位“异或”Bitwise XOR 5 -bxor 3
-shl-shl 将位向左移动Shifts bits to the left 102 -shl 2
-shr-shr 将位向右移位Shifts bits to the right 102 -shr 2

按位运算符仅适用于整数类型。The bitwise operators only work on integer types.

运算符优先级OPERATOR PRECEDENCE

PowerShell 按以下顺序处理算术运算符:PowerShell processes arithmetic operators in the following order:

优先级Precedence 运算符Operator 说明Description
11 () 括号Parentheses
22 - 对于负数或一元运算符For a negative number or unary operator
33 *, /, %*, /, % 对于乘法和除法For multiplication and division
44 +, -+, - 对于加法和减法For addition and subtraction
55 -band, -bnot-band, -bnot 对于按位运算For bitwise operations
55 -bor, -bxor-bor, -bxor 对于按位运算For bitwise operations
55 -shr, -shl-shr, -shl 对于按位运算For bitwise operations

根据优先级规则,PowerShell 从左到右处理表达式。PowerShell processes the expressions from left to right according to the precedence rules. 以下示例显示了优先规则的效果:The following examples show the effect of the precedence rules:

表达式Expression 结果Result
3+6/3*4 11
3+6/(3*4) 3.5
(3+6)/3*4 12

PowerShell 计算表达式的顺序可能不同于你使用的其他编程和脚本语言。The order in which PowerShell evaluates expressions might differ from other programming and scripting languages that you have used. 下面的示例演示了复杂的赋值语句。The following example shows a complicated assignment statement.

$a = 0
$b = @(1,2)
$c = @(-1,-2)

$b[$a] = $c[$a++]

在此示例中,对表达式 $a++ 进行计算 $b[$a]In this example, the expression $a++ is evaluated before $b[$a]. $a++ $a 语句中使用之后,计算更改的值, $c[$a++] 但在中使用它之前 $b[$a]Evaluating $a++ changes the value of $a after it is used in the statement $c[$a++]; but, before it is used in $b[$a]. 中的 $a 变量 $b[$a] 等于 1 ,而不是 0 ; 因此,语句将值赋给 $b[1] ,而不是 $b[0]The variable $a in $b[$a] equals 1, not 0; so, the statement assigns a value to $b[1], not $b[0].

上述代码等效于:The above code is equivalent to:

$a = 0
$b = @(1,2)
$c = @(-1,-2)

$tmp = $c[$a]
$a = $a + 1
$b[$a] = $tmp

相除和舍入DIVISION AND ROUNDING

当除法运算的商是整数时,PowerShell 会将值舍入到最接近的整数。When the quotient of a division operation is an integer, PowerShell rounds the value to the nearest integer. 如果值为 .5 ,则它将舍入到最接近的偶数。When the value is .5, it rounds to the nearest even integer.

下面的示例演示舍入到最接近的偶数的效果。The following example shows the effect of rounding to the nearest even integer.

表达式Expression 结果Result
[int]( 5 / 2 ) 2
[int]( 7 / 2 ) 4

请注意 5/2 = 2.5 舍入到 2 的方式。Notice how 5/2 = 2.5 gets rounded to 2 . 7/2 = 3.5 舍入为 4But, 7/2 = 3.5 gets rounded to 4 .

您可以使用 [Math] 类来获取不同的舍入行为。You can use the [Math] class to get different rounding behavior.

表达式Expression 结果Result
[int][Math]::Round(5 / 2,[MidpointRounding]::AwayFromZero) 3
[int][Math]::Ceiling(5 / 2) 3
[int][Math]::Floor(5 / 2) 2

有关详细信息,请参阅 Math 方法。For more information, see the Math.Round method.

添加非数值类型和相乘ADDING AND MULTIPLYING NON-NUMERIC TYPES

可以添加数字、字符串、数组和哈希表。You can add numbers, strings, arrays, and hash tables. 而且,您可以将数字、字符串和数组相乘。And, you can multiply numbers, strings, and arrays. 但是,不能将哈希表相乘。However, you cannot multiply hash tables.

添加字符串、数组或哈希表时,这些元素将连接在一起。When you add strings, arrays, or hash tables, the elements are concatenated. 当连接集合(如数组或哈希表)时,将创建一个新的对象,该对象包含两个集合中的对象。When you concatenate collections, such as arrays or hash tables, a new object is created that contains the objects from both collections. 如果尝试连接具有相同键的哈希表,则操作将失败。If you try to concatenate hash tables that have the same key, the operation fails.

例如,下面的命令创建两个数组,然后添加它们:For example, the following commands create two arrays and then add them:

$a = 1,2,3
$b = "A","B","C"
$a + $b
1
2
3
A
B
C

您还可以对不同类型的对象执行算术运算。You can also perform arithmetic operations on objects of different types. PowerShell 执行的操作由操作中最左边对象的 Microsoft .NET 框架类型决定。The operation that PowerShell performs is determined by the Microsoft .NET Framework type of the leftmost object in the operation. PowerShell 尝试将操作中的所有对象转换为第一个对象的 .NET Framework 类型。PowerShell tries to convert all the objects in the operation to the .NET Framework type of the first object. 如果它成功转换了对象,它将执行适用于第一个对象的 .NET Framework 类型的操作。If it succeeds in converting the objects, it performs the operation appropriate to the .NET Framework type of the first object. 如果无法转换任何对象,操作将失败。If it fails to convert any of the objects, the operation fails.

下面的示例演示加法和乘法运算符的用法;在包含不同对象类型的操作中。The following examples demonstrate the use of the addition and multiplication operators; in operations that include different object types. 假定 $array = 1,2,3Assume $array = 1,2,3:

表达式Expression 结果Result
"file" + 16 file16
$array + 16 1,2,3,161,2,3,16
$array + "file" 1,2,3,file1,2,3,file
$array * 2 1,2,3,1,2,31,2,3,1,2,3
"file" * 3 filefilefile

因为用于计算语句的方法由最左端的对象确定,所以 PowerShell 中的加法和乘法并不完全是可交换的。Because the method that is used to evaluate statements is determined by the leftmost object, addition and multiplication in PowerShell are not strictly commutative. 例如,并不 (a + b) 总是相等 (b + a) ,并且不 (ab) 始终相等 (ba)For example, (a + b) does not always equal (b + a), and (ab) does not always equal (ba).

下面的示例演示了这一原则:The following examples demonstrate this principle:

表达式Expression 结果Result
"file" + 16 file16
16 + "file" Cannot convert value "file" to type "System.Int32".
Error: "Input string was not in a correct format."
At line:1 char:1
+ 16 + "file"+ 16 + "file"`

哈希表的大小写略有不同。Hash tables are a slightly different case. 您可以将哈希表添加到另一个哈希表,前提是已添加的哈希表没有重复键。You can add hash tables to another hash table, as long as, the added hash tables don't have duplicate keys.

下面的示例演示如何向彼此添加哈希表。The following example show how to add hash tables to each other.

$hash1 = @{a=1; b=2; c=3}
$hash2 = @{c1="Server01"; c2="Server02"}
$hash1 + $hash2
Name                           Value
----                           -----
c2                             Server02
a                              1
b                              2
c1                             Server01
c                              3

下面的示例引发错误,因为这两个哈希表中的一个键重复。The following example throws an error because one of the keys is duplicated in both hash tables.

$hash1 = @{a=1; b=2; c=3}
$hash2 = @{c1="Server01"; c="Server02"}
$hash1 + $hash2
Item has already been added. Key in dictionary: 'c'  Key being added: 'c'
At line:3 char:1
+ $hash1 + $hash2
+ ~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], ArgumentException
    + FullyQualifiedErrorId : System.ArgumentException

此外,还可以将哈希表添加到数组;而且,整个哈希表将成为数组中的项。Also, you can add a hash table to an array; and, the entire hash table becomes an item in the array.

$array1 = @(0, "Hello World", [datetime]::Now)
$hash1 = @{a=1; b=2}
$array2 = $array1 + $hash1
$array2
0
Hello World

Monday, June 12, 2017 3:05:46 PM

Key   : a
Value : 1
Name  : a

Key   : b
Value : 2
Name  : b

但是,不能将任何其他类型添加到哈希表。However, you cannot add any other type to a hash table.

$hash1 + 2
A hash table can only be added to another hash table.
At line:3 char:1
+ $hash1 + 2

虽然加法运算符非常有用,但使用赋值运算符将元素添加到哈希表和数组。Although the addition operators are very useful, use the assignment operators to add elements to hash tables and arrays. 有关详细信息,请参阅 about_assignment_operatorsFor more information see about_assignment_operators. 下面的示例使用 += 赋值运算符将项添加到数组中:The following examples use the += assignment operator to add items to an array:

$array = @()
(0..9).foreach{ $array += $_ }
$array
0
1
2

用于容纳结果的类型转换TYPE CONVERSION TO ACCOMMODATE RESULT

PowerShell 会自动选择最能表达结果的 .NET Framework 数值类型,而不会丢失精度。PowerShell automatically selects the .NET Framework numeric type that best expresses the result without losing precision. 例如:For example:

2 + 3.1

(2). GetType().FullName
(2 + 3.1).GetType().FullName
5.1
System.Int32
System.Double

如果操作的结果对于类型太大,则结果的类型会扩大以容纳结果,如以下示例中所示:If the result of an operation is too large for the type, the type of the result is widened to accommodate the result, as in the following example:

(512MB).GetType().FullName
(512MB * 512MB).GetType().FullName
System.Int32
System.Double

结果的类型不一定与操作数之一相同。The type of the result will not necessarily be the same as one of the operands. 在下面的示例中,负值不能转换为无符号整数,且无符号整数太大,无法强制转换为 Int32In the following example, the negative value cannot be cast to an unsigned integer, and the unsigned integer is too large to be cast to Int32:

([int32]::minvalue + [uint32]::maxvalue).gettype().fullname
System.Int64

在此示例中, Int64 可以同时容纳这两种类型。In this example, Int64 can accommodate both types.

System.Decimal类型为异常。The System.Decimal type is an exception. 如果任一操作数具有 Decimal 类型,则结果将为 Decimal 类型。If either operand has the Decimal type, the result will be of the Decimal type. 如果结果对 Decimal 类型来说太大,则不会将其强制转换为 Double 类型。If the result is too large for the Decimal type, it will not be cast to Double. 相反,会产生错误。Instead, an error results.

表达式Expression 结果Result
[Decimal]::maxvalue 79228162514264337593543950335
[Decimal]::maxvalue + 1 Value was either too large or too small for a
Decimal.

算术运算符和变量ARITHMETIC OPERATORS AND VARIABLES

还可以对变量使用算术运算符。You can also use arithmetic operators with variables. 运算符作用于变量的值。The operators act on the values of the variables. 下面的示例演示如何对变量使用算术运算符:The following examples demonstrate the use of arithmetic operators with variables:

表达式Expression 结果Result
$intA = 6
$intB = 4
$intA + $intB
10
$a = "Power"
$b = "Shell"
$a + $b
PowerShell

算术运算符和命令ARITHMETIC OPERATORS AND COMMANDS

通常,可以在表达式中使用数字、字符串和数组的算术运算符。Typically, you use the arithmetic operators in expressions with numbers, strings, and arrays. 但是,还可以将算术运算符与命令返回的对象以及这些对象的属性一起使用。However, you can also use arithmetic operators with the objects that commands return and with the properties of those objects.

下面的示例演示如何在表达式中通过 PowerShell 命令使用算术运算符:The following examples show how to use the arithmetic operators in expressions with PowerShell commands:

(get-date) + (new-timespan -day 1)

圆括号运算符 get-date 按顺序强制对 cmdlet 和 cmdlet 表达式的计算进行计算 new-timespan -day 1The parenthesis operator forces the evaluation of the get-date cmdlet and the evaluation of the new-timespan -day 1 cmdlet expression, in that order. 然后使用运算符添加两个结果 +Both results are then added using the + operator.

Get-Process | Where-Object { ($_.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

在上述表达式中, () 的每个进程工作空间 $_.ws 都将乘以 2 ; 与结果相比, 50mb 它们是否大于该值。In the above expression, each process working space ($_.ws) is multiplied by 2; and, the result, compared against 50mb to see if it is greater than that.

位运算符Bitwise Operators

PowerShell 支持标准按位运算符,包括按位与 (-bAnd) 、 (和) 的非独占和独占按位或运算符 -bOr-bXor 以及按位 "非 () -bNotPowerShell supports the standard bitwise operators, including bitwise-AND (-bAnd), the inclusive and exclusive bitwise-OR operators (-bOr and -bXor), and bitwise-NOT (-bNot).

从 PowerShell 2.0 开始,所有位运算符都适用于64位整数。Beginning in PowerShell 2.0, all bitwise operators work with 64-bit integers.

从 PowerShell 3.0 开始, -shr 会引入 (向右) 和 -shl (左移) ,以支持在 PowerShell 中进行按位运算。Beginning in PowerShell 3.0, the -shr (shift-right) and -shl (shift-left) are introduced to support bitwise arithmetic in PowerShell.

PowerShell 支持以下按位运算符。PowerShell supports the following bitwise operators.

运算符Operator 说明Description 表达式Expression 结果Result
-band 位与Bitwise AND 10 -band 3 22
-bor 按位 OR (包含) Bitwise OR (inclusive) 10 -bor 3 1111
-bxor 按位或 (独占) Bitwise OR (exclusive) 10 -bxor 3 99
-bnot 按位“非”Bitwise NOT -bNot 10 -11-11
-shl 左移Shift-left 102 -shl 2 408408
-shr 向右移动Shift-right 102 -shr 1 5151

位运算符作用于值的二进制格式。Bitwise operators act on the binary format of a value. 例如,数字10的位结构为 00001010 (基于1个字节) ,数字3的位结构是00000011。For example, the bit structure for the number 10 is 00001010 (based on 1 byte), and the bit structure for the number 3 is 00000011. 当使用位运算符将10与3进行比较时,将比较每个字节中的单个位。When you use a bitwise operator to compare 10 to 3, the individual bits in each byte are compared.

在按位 "与" 运算中,只有当两个输入位均为1时,才将生成的位设置为1。In a bitwise AND operation, the resulting bit is set to 1 only when both input bits are 1.

1010      (10)
0011      ( 3)
--------------  bAND
0010      ( 2)

在按位 "或" (包含) "操作中,如果其中一个或两个输入位均为1,则生成的位将设置为1。In a bitwise OR (inclusive) operation, the resulting bit is set to 1 when either or both input bits are 1. 仅当两个输入位均设置为0时,结果位设置为0。The resulting bit is set to 0 only when both input bits are set to 0.

1010      (10)
0011      ( 3)
--------------  bOR (inclusive)
1011      (11)

在按位或 (独占) 操作中,仅当一个输入位为1时,结果位将设置为1。In a bitwise OR (exclusive) operation, the resulting bit is set to 1 only when one input bit is 1.

1010      (10)
0011      ( 3)
--------------  bXOR (exclusive)
1001      ( 9)

按位 "非" 运算符是一个一元运算符,该运算符产生值的二进制补码。The bitwise NOT operator is a unary operator that produces the binary complement of the value. 1的位设置为0,位0设置为1。A bit of 1 is set to 0 and a bit of 0 is set to 1.

例如,0的二进制反码为-1,最大无符号整数 (0xffffffff) ,二进制补码-1 为0。For example, the binary complement of 0 is -1, the maximum unsigned integer (0xffffffff), and the binary complement of -1 is 0.

-bNot 10
-11
0000 0000 0000 1010  (10)
------------------------- bNOT
1111 1111 1111 0101  (-11, xfffffff5)

在按位左移操作时,所有位都向左移动 "n",其中 "n" 是右操作数的值。In a bitwise shift-left operation, all bits are moved "n" places to the left, where "n" is the value of the right operand. 在一个位置插入零。A zero is inserted in the ones place.

当左操作数是一个整数 (32 位) 值时,右操作数的下5位将确定左操作数的位移位数。When the left operand is an Integer (32-bit) value, the lower 5 bits of the right operand determine how many bits of the left operand are shifted.

当左操作数为长 (64 位) 值时,右操作数的低6位确定左操作数的偏移量。When the left operand is a Long (64-bit) value, the lower 6 bits of the right operand determine how many bits of the left operand are shifted.

表达式Expression 结果Result 二进制结果Binary Result
21 -shl 0 2121 0001 01010001 0101
21 -shl 1 4242 0010 10100010 1010
21 -shl 2 8484 0101 01000101 0100

在按位右移操作中,所有位都将 "n" 向右移动,其中 "n" 由右操作数指定。In a bitwise shift-right operation, all bits are moved "n" places to the right, where "n" is specified by the right operand. 向右移动运算符 (-shr) 在将正或无符号值向右移位时,将在最左侧插入零。The shift-right operator (-shr) inserts a zero in the left-most place when shifting a positive or unsigned value to the right.

当左操作数是一个整数 (32 位) 值时,右操作数的下5位将确定左操作数的位移位数。When the left operand is an Integer (32-bit) value, the lower 5 bits of the right operand determine how many bits of the left operand are shifted.

当左操作数为长 (64 位) 值时,右操作数的低6位确定左操作数的偏移量。When the left operand is a Long (64-bit) value, the lower 6 bits of the right operand determine how many bits of the left operand are shifted.

表达式Expression 结果Result 二进制Binary HexHex
21 -shr 0 2121 0001 01010001 0101 0x150x15
21 -shr 1 1010 0000 10100000 1010 0x0A0x0A
21 -shr 2 55 0000 01010000 0101 0x050x05
21 -shr 31 00 0000 00000000 0000 0x000x00
21 -shr 32 2121 0001 01010001 0101 0x150x15
21 -shr 64 2121 0001 01010001 0101 0x150x15
21 -shr 65 1010 0000 10100000 1010 0x0A0x0A
21 -shr 66 55 0000 01010000 0101 0x050x05
[int]::MaxValue -shr 1 10737418231073741823 0x3FFFFFFF0x3FFFFFFF
[int]::MinValue -shr 1 -1073741824-1073741824 0xC00000000xC0000000
-1 -shr 1 -1-1 0xFFFFFFFF0xFFFFFFFF

另请参阅SEE ALSO