关于运算符About Operators

简短说明Short description

描述 PowerShell 支持的运算符。Describes the operators that are supported by PowerShell.

长说明Long description

运算符是可在命令或表达式中使用的语言元素。An operator is a language element that you can use in a command or expression. PowerShell 支持多种类型的运算符来帮助您操作值。PowerShell supports several types of operators to help you manipulate values.

算术运算符Arithmetic Operators

使用算术运算符 (+-*/ %) 计算命令或表达式中的值。Use arithmetic operators (+, -, *, /, %) to calculate values in a command or expression. 使用这些运算符,可以添加、减、乘或相除值,计算除法运算的余数 (模数) 。With these operators, you can add, subtract, multiply, or divide values, and calculate the remainder (modulus) of a division operation.

加法运算符用于连接元素。The addition operator concatenates elements. 乘法运算符返回每个元素的指定数量的副本。The multiplication operator returns the specified number of copies of each element. 可以对任何实现它们的 .net 类型使用算术运算符,例如: IntStringDateTimeHashtable 和数组。You can use arithmetic operators on any .NET type that implements them, such as: Int, String, DateTime, Hashtable, and Arrays.

按位运算符 (-band 、、、、 -bor -bxor -bnot -shl -shr) 处理值中的位模式。Bitwise operators (-band, -bor, -bxor, -bnot, -shl, -shr) manipulate the bit patterns in values.

有关详细信息,请参阅 about_Arithmetic_OperatorsFor more information, see about_Arithmetic_Operators.

赋值运算符Assignment Operators

使用赋值运算符 (=+=-=*=/=%=) 将值分配给变量或将值追加到变量。Use assignment operators (=, +=, -=, *=, /=, %=) to assign, change, or append values to variables. 可以将算术运算符与赋值结合使用,将算术运算的结果分配给变量。You can combine arithmetic operators with assignment to assign the result of the arithmetic operation to a variable.

有关详细信息,请参阅 about_Assignment_OperatorsFor more information, see about_Assignment_Operators.

比较运算符Comparison Operators

使用比较运算符 (-eq 、、、、、 -ne -gt -lt -le -ge) 比较值和测试条件。Use comparison operators (-eq, -ne, -gt, -lt, -le, -ge) to compare values and test conditions. 例如,可以比较两个字符串值,以确定它们是否相等。For example, you can compare two string values to determine whether they are equal.

比较运算符还包括用于在文本中查找或替换模式的运算符。The comparison operators also include operators that find or replace patterns in text. (-match-notmatch -replace) 运算符使用正则表达式和 (-like-notlike) 使用通配符 *The (-match, -notmatch, -replace) operators use regular expressions, and (-like, -notlike) use wildcards *.

包含比较运算符确定测试值是出现在引用集中, (,,, -in -notin -contains -notcontains) 。Containment comparison operators determine whether a test value appears in a reference set (-in, -notin, -contains, -notcontains).

类型比较运算符 (-is-isnot) 确定对象是否为给定类型。Type comparison operators (-is, -isnot) determine whether an object is of a given type.

有关详细信息,请参阅 about_Comparison_OperatorsFor more information, see about_Comparison_Operators.

逻辑运算符Logical Operators

使用逻辑运算符 (-and-or-xor-not !) 将条件语句连接到单个复杂条件。Use logical operators (-and, -or, -xor, -not, !) to connect conditional statements into a single complex conditional. 例如,可以使用逻辑 -and 运算符创建具有两个不同条件的对象筛选器。For example, you can use a logical -and operator to create an object filter with two different conditions.

有关详细信息,请参阅 about_Logical_OperatorsFor more information, see about_Logical_Operators.

重定向运算符Redirection Operators

使用重定向运算符 (>>>2>2>>2>&1) 将命令或表达式的输出发送到文本文件。Use redirection operators (>, >>, 2>, 2>>, and 2>&1) to send the output of a command or expression to a text file. 重定向运算符的工作方式类似于 Out-File 不带参数的 cmdlet () 但是,它们还允许你将错误输出重定向到指定的文件。The redirection operators work like the Out-File cmdlet (without parameters) but they also let you redirect error output to specified files. 你还可以使用 Tee-Object cmdlet 来重定向输出。You can also use the Tee-Object cmdlet to redirect output.

有关详细信息,请参阅 about_RedirectionFor more information, see about_Redirection

拆分和联接运算符Split and Join Operators

-split-join 运算符划分并组合子字符串。The -split and -join operators divide and combine substrings. -split运算符将字符串拆分为子字符串。The -split operator splits a string into substrings. -join运算符将多个字符串串联为一个字符串。The -join operator concatenates multiple strings into a single string.

有关详细信息,请参阅 about_Splitabout_JoinFor more information, see about_Split and about_Join.

类型运算符Type Operators

使用 (,) 的类型运算符 -is -isnot -as 查找或更改对象的 .NET Framework 类型。Use the type operators (-is, -isnot, -as) to find or change the .NET Framework type of an object.

有关详细信息,请参阅 about_Type_OperatorsFor more information, see about_Type_Operators.

一元运算符Unary Operators

使用一元运算符来递增或递减变量或对象属性,并将整数设置为正数或负数。Use unary operators to increment or decrement variables or object properties and to set integers to positive or negative numbers. 例如,若要将变量 $a 从增加 910 ,请键入 $a++For example, to increment the variable $a from 9 to 10, you type $a++.

特殊运算符Special Operators

特殊运算符具有不适合任何其他操作员组的特定用例。Special operators have specific use-cases that do not fit into any other operator group. 例如,使用特殊运算符可运行命令、更改值的数据类型或从数组中检索元素。For example, special operators allow you to run commands, change a value's data type, or retrieve elements from an array.

分组运算符 ( )Grouping operator ( )

与其他语言一样, (...) 用于重写表达式中的运算符优先级。As in other languages, (...) serves to override operator precedence in expressions. 例如: (1 + 2) / 3For example: (1 + 2) / 3

但是,在 PowerShell 中还有其他行为。However, in PowerShell, there are additional behaviors.

  • (...) 允许您允许 命令 的输出参与表达式。(...) allows you to let output from a command participate in an expression. 例如:For example:

    PS> (Get-Item *.txt).Count -gt 10
    True
    
  • 当用作管道的第一段时,用括号将命令或表达式括起来会导致表达式结果的 枚举When used as the first segment of a pipeline, wrapping a command or expression in parentheses invariably causes enumeration of the expression result. 如果括号环绕 命令,则在通过管道发送结果之前,将使用 内存中收集 的所有输出运行完成。If the parentheses wrap a command, it is run to completion with all output collected in memory before the results are sent through the pipeline.

子表达式运算符 $( )Subexpression operator $( )

返回一个或多个语句的结果。Returns the result of one or more statements. 对于单个结果,返回一个标量。For a single result, returns a scalar. 对于多个结果,将返回一个数组。For multiple results, returns an array. 如果要在另一个表达式内使用表达式,请使用此表达式。Use this when you want to use an expression within another expression. 例如,要在字符串表达式中嵌入命令的结果。For example, to embed the results of command in a string expression.

PS> "Today is $(Get-Date)"
Today is 12/02/2019 13:15:20

PS> "Folder list: $((dir c:\ -dir).Name -join ', ')"
Folder list: Program Files, Program Files (x86), Users, Windows

Array 子表达式运算符 @( )Array subexpression operator @( )

以数组形式返回一个或多个语句的结果。Returns the result of one or more statements as an array. 如果只有一个项,则数组只包含一个成员。If there is only one item, the array has only one member.

@(Get-CimInstance win32_logicalDisk)

哈希表文本语法 @{}Hash table literal syntax @{}

与 array 子表达式类似,此语法用于声明哈希表。Similar to the array subexpression, this syntax is used to declare a hash table. 有关详细信息,请参阅 about_Hash_TablesFor more information, see about_Hash_Tables.

Call 运算符 &Call operator &

运行命令、脚本或脚本块。Runs a command, script, or script block. Call 运算符(也称为 "调用运算符")允许您运行存储在变量中并由字符串或脚本块表示的命令。The call operator, also known as the "invocation operator", lets you run commands that are stored in variables and represented by strings or script blocks. 调用运算符在子范围内执行。The call operator executes in a child scope. 有关范围的详细信息,请参阅 about_ScopesFor more about scopes, see about_Scopes.

此示例将命令存储在字符串中,并使用 call 运算符执行该命令。This example stores a command in a string and executes it using the call operator.

PS> $c = "get-executionpolicy"
PS> $c
get-executionpolicy
PS> & $c
AllSigned

调用运算符不分析字符串。The call operator does not parse strings. 这意味着,在使用 call 运算符时,不能使用字符串中的命令参数。This means that you cannot use command parameters within a string when you use the call operator.

PS> $c = "Get-Service -Name Spooler"
PS> $c
Get-Service -Name Spooler
PS> & $c
& : The term 'Get-Service -Name Spooler' is not recognized as the name of a
cmdlet, function, script file, or operable program. Check the spelling of
the name, or if a path was included, verify that the path is correct and
try again.

调用表达式cmdlet 可执行在使用 call 运算符时导致分析错误的代码。The Invoke-Expression cmdlet can execute code that causes parsing errors when using the call operator.

PS> & "1+1"
& : The term '1+1' is not recognized as the name of a cmdlet, function, script
file, or operable program. Check the spelling of the name, or if a path was
included, verify that the path is correct and try again.
At line:1 char:2
+ & "1+1"
+  ~~~~~
    + CategoryInfo          : ObjectNotFound: (1+1:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
PS> Invoke-Expression "1+1"
2

可以使用 call 运算符来执行使用其文件名的脚本。You can use the call operator to execute scripts using their filenames. 下面的示例显示了包含空格的脚本文件名。The example below shows a script filename that contains spaces. 当你尝试执行脚本时,PowerShell 将显示包含文件名的带引号的字符串的内容。When you try to execute the script, PowerShell instead displays the contents of the quoted string containing the filename. Call 运算符用于执行包含文件名的字符串的内容。The call operator allows you to execute the contents of the string containing the filename.

PS C:\Scripts> Get-ChildItem

    Directory: C:\Scripts


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----        8/28/2018   1:36 PM             58 script name with spaces.ps1

PS C:\Scripts> ".\script name with spaces.ps1"
.\script name with spaces.ps1
PS C:\Scripts> & ".\script name with spaces.ps1"
Hello World!

有关脚本块的详细信息,请参阅 about_Script_BlocksFor more about script blocks, see about_Script_Blocks.

后台运算符 &Background operator &

在 PowerShell 作业中,在后台运行管道。Runs the pipeline before it in the background, in a PowerShell job. 此运算符的行为类似于 UNIX control 运算符 and (&) ,它在 subshell 中以异步方式运行命令作为作业。This operator acts similarly to the UNIX control operator ampersand (&), which runs the command before it asynchronously in subshell as a job.

此运算符在功能上等效于 Start-JobThis operator is functionally equivalent to Start-Job. 默认情况下,后台运算符启动启动并行任务的调用方的当前工作目录中的作业。By default, the background operator starts the jobs in the current working directory of the caller that started the parallel tasks. 下面的示例演示后台作业运算符的基本用法。The following example demonstrates basic usage of the background job operator.

Get-Process -Name pwsh &

此命令在功能上等同于以下用法 Start-JobThat command is functionally equivalent to the following usage of Start-Job:

Start-Job -ScriptBlock {Get-Process -Name pwsh}

就像一样 Start-Job& 后台运算符返回 Job 对象。Just like Start-Job, the & background operator returns a Job object. 此对象可与和一起 Receive-Job 使用 Remove-Job ,就像你已使用 Start-Job 来启动该作业一样。This object can be used with Receive-Job and Remove-Job, just as if you had used Start-Job to start the job.

$job = Get-Process -Name pwsh &
Receive-Job $job -Wait

 NPM(K)    PM(M)      WS(M)     CPU(s)      Id  SI ProcessName
 ------    -----      -----     ------      --  -- -----------
      0     0.00     221.16      25.90    6988 988 pwsh
      0     0.00     140.12      29.87   14845 845 pwsh
      0     0.00      85.51       0.91   19639 988 pwsh

Remove-Job $job

&后台运算符也是语句终止符,就像) (的 UNIX 控件运算符 "and" &The & background operator is also a statement terminator, just like the UNIX control operator ampersand (&). 这允许您在后台运算符之后调用其他命令 &This allows you to invoke additional commands after the & background operator. 下面的示例演示如何在后台运算符之后调用其他命令 &The following example demonstrates the invocation of additional commands after the & background operator.

$job = Get-Process -Name pwsh & Receive-Job $job -Wait

 NPM(K)    PM(M)      WS(M)     CPU(s)      Id  SI ProcessName
 ------    -----      -----     ------      --  -- -----------
      0     0.00     221.16      25.90    6988 988 pwsh
      0     0.00     140.12      29.87   14845 845 pwsh
      0     0.00      85.51       0.91   19639 988 pwsh

这等效于以下脚本:This is equivalent to the following script:

$job = Start-Job -ScriptBlock {Get-Process -Name pwsh}
Receive-Job $job -Wait

如果要运行多个命令,每个命令都在其自己的后台进程中,但全部在一行上,只需在 & 每个命令前后放置。If you want to run multiple commands, each in their own background process but all on one line, simply place & between and after each of the commands.

Get-Process -Name pwsh & Get-Service -Name BITS & Get-CimInstance -ClassName Win32_ComputerSystem &

有关 PowerShell 作业的详细信息,请参阅 about_JobsFor more information on PowerShell jobs, see about_Jobs.

Cast 运算符 [ ]Cast operator [ ]

将对象转换或限制为指定的类型。Converts or limits objects to the specified type. 如果无法转换对象,PowerShell 会生成错误。If the objects cannot be converted, PowerShell generates an error.

[DateTime]"2/20/88" - [DateTime]"1/20/88"
[Int] (7/2)
[String] 1 + 0
[Int] '1' + 0

使用 强制转换表示法赋值时,还可以执行强制转换。A cast can also be performed when a variable is assigned to using cast notation.

逗号运算符 ,Comma operator ,

作为二元运算符,逗号创建数组或追加到所创建的数组。As a binary operator, the comma creates an array or appends to the array being created. 在表达式模式下,作为一元运算符,逗号创建只包含一个成员的数组。In expression mode, as a unary operator, the comma creates an array with just one member. 将逗号置于成员前面。Place the comma before the member.

$myArray = 1,2,3
$SingleArray = ,1
Write-Output (,1)

由于 Write-Object 需要参数,因此必须将表达式放在括号中。Since Write-Object expects an argument, you must put the expression in parentheses.

网点采购运算符 .Dot sourcing operator .

在当前作用域中运行脚本,以便将脚本创建的所有函数、别名和变量添加到当前作用域中,并覆盖现有作用域。Runs a script in the current scope so that any functions, aliases, and variables that the script creates are added to the current scope, overriding existing ones. 脚本声明的参数成为变量。Parameters declared by the script become variables. 未为其提供值的参数将成为没有值的变量。Parameters for which no value has been given become variables with no value. 但是, $args 会保留自动变量。However, the automatic variable $args is preserved.

. c:\scripts\sample.ps1 1 2 -Also:3

备注

点采购运算符后跟一个空格。The dot sourcing operator is followed by a space. 使用空格将点与表示当前目录的点 (.) 符号区分开来。Use the space to distinguish the dot from the dot (.) symbol that represents the current directory.

在下面的示例中,当前目录中的 Sample.ps1 脚本在当前作用域中运行。In the following example, the Sample.ps1 script in the current directory is run in the current scope.

. .\sample.ps1

Format 运算符 -fFormat operator -f

使用字符串对象的 format 方法格式化字符串。Formats strings by using the format method of string objects. 在运算符的左侧输入格式字符串,并在运算符右侧输入要设置格式的对象。Enter the format string on the left side of the operator and the objects to be formatted on the right side of the operator.

"{0} {1,-10} {2:N}" -f 1,"hello",[math]::pi
1 hello      3.14

如果需要 {} 在带格式的字符串中保留大括号 () ,可以通过将大括号加倍来对它们进行转义。If you need to keep the curly braces ({}) in the formatted string, you can escape them by doubling the curly braces.

"{0} vs. {{0}}" -f 'foo'
foo vs. {0}

有关详细信息,请参阅 字符串格式 方法和 复合格式设置For more information, see the String.Format method and Composite Formatting.

Index 运算符 [ ]Index operator [ ]

从索引集合中选择对象,如数组和哈希表。Selects objects from indexed collections, such as arrays and hash tables. 数组索引是从零开始的,因此第一个对象的索引为 [0]Array indexes are zero-based, so the first object is indexed as [0]. 对于仅) (数组,还可以使用负索引来获取最后一个值。For arrays (only), you can also use negative indexes to get the last values. 哈希表按键值编制索引。Hash tables are indexed by key value.

PS> $a = 1, 2, 3
PS> $a[0]
1
PS> $a[-1]
3
(Get-HotFix | Sort-Object installedOn)[-1]
$h = @{key="value"; name="PowerShell"; version="2.0"}
$h["name"]
PowerShell
$x = [xml]"<doc><intro>Once upon a time...</intro></doc>"
$x["doc"]
intro
-----
Once upon a time...

管道运算符 |Pipeline operator |

将 ( "管道" ) 命令的输出发送到其后的命令。Sends ("pipes") the output of the command that precedes it to the command that follows it. 如果输出中包含一个 "集合" ) (多个对象,则管道运算符每次发送一个对象。When the output includes more than one object (a "collection"), the pipeline operator sends the objects one at a time.

Get-Process | Get-Member
Get-Service | Where-Object {$_.StartType -eq 'Automatic'}

管道链运算符 &&||Pipeline chain operators && and ||

根据左侧管道的成功,有条件地执行右侧管道。Conditionally execute the right-hand side pipeline based on the success of the left-hand side pipeline.

# If Get-Process successfully finds a process called notepad,
# Stop-Process -Name notepad is called
Get-Process notepad && Stop-Process -Name notepad
# If npm install fails, the node_modules directory is removed
npm install || Remove-Item -Recurse ./node_modules

有关详细信息,请参阅 About_Pipeline_Chain_OperatorsFor more information, see About_Pipeline_Chain_Operators.

范围运算符 ..Range operator ..

表示整数数组中的顺序整数(给定上下限)。Represents the sequential integers in an integer array, given an upper, and lower boundary.

1..10
foreach ($a in 1..$max) {Write-Host $a}

您还可以按相反的顺序创建范围。You can also create ranges in reverse order.

10..1
5..-5 | ForEach-Object {Write-Output $_}

从 PowerShell 6 开始,range 运算符使用 字符整数Beginning in PowerShell 6, the range operator works with Characters as well as Integers.

若要创建字符范围,请将边界字符括在引号中。To create a range of characters, enclose the boundary characters in quotes.

PS> 'a'..'f'
a
b
c
d
e
f
PS> 'F'..'A'
F
E
D
C
B
A

成员访问运算符 .Member access operator .

访问对象的属性和方法。Accesses the properties and methods of an object. 成员名称可以是表达式。The member name may be an expression.

$myProcess.peakWorkingSet
(Get-Process PowerShell).kill()
'OS', 'Platform' | Foreach-Object { $PSVersionTable. $_ }

静态成员运算符 ::Static member operator ::

调用 .NET Framework 类的静态属性和方法。Calls the static properties and methods of a .NET Framework class. 若要查找对象的静态属性和方法,请使用 cmdlet 的静态参数 Get-MemberTo find the static properties and methods of an object, use the Static parameter of the Get-Member cmdlet. 成员名称可以是表达式。The member name may be an expression.

[datetime]::Now
'MinValue', 'MaxValue' | Foreach-Object { [int]:: $_ }

三元运算符 ? <if-true> : <if-false>Ternary operator ? <if-true> : <if-false>

在简单的条件情况下,可以使用三元运算符替换 if-else 语句。You can use the ternary operator as a replacement for the if-else statement in simple conditional cases.

有关详细信息,请参阅 about_IfFor more information, see about_If.

Null 合并运算符 ??Null-coalescing operator ??

如果 null 合并运算符 ?? 不为 null,则它返回其左操作数的值。The null-coalescing operator ?? returns the value of its left-hand operand if it isn't null. 否则,它将计算右操作数并返回其结果。Otherwise, it evaluates the right-hand operand and returns its result. 如果左操作数的计算结果为非 null,则 ?? 运算符不会计算其右操作数。The ?? operator doesn't evaluate its right-hand operand if the left-hand operand evaluates to non-null.

$x = $null
$x ?? 100
100

在下面的示例中,不会计算右侧的操作数。In the following example, the right-hand operand won't be evaluated.

[string] $todaysDate = '1/10/2020'
$todaysDate ?? (Get-Date).ToShortDateString()
1/10/2020

Null 合并赋值运算符 ??=Null-coalescing assignment operator ??=

??=如果左操作数的计算结果为 null,则 null 合并赋值运算符仅将其右操作数的值分配给其左操作数。The null-coalescing assignment operator ??= assigns the value of its right-hand operand to its left-hand operand only if the left-hand operand evaluates to null. 如果左操作数的计算结果为非 null,则 ??= 运算符不会计算其右操作数。The ??= operator doesn't evaluate its right-hand operand if the left-hand operand evaluates to non-null.

$x = $null
$x ??= 100
$x
100

在下面的示例中,不会计算右侧的操作数。In the following example, the right-hand operand won't be evaluated.

[string] $todaysDate = '1/10/2020'
$todaysDate ??= (Get-Date).ToShortDateString()
1/10/2020

Null 条件运算符 ?.?[]Null-conditional operators ?. and ?[]

备注

此功能已从实验迁移到 PowerShell 7.1 中的主流。This feature was moved from experimental to mainstream in PowerShell 7.1.

?.只有当操作数的计算结果为非 null 时,null 条件运算符才会将成员访问、或元素访问权限应用于 ?[] 其操作数; 否则,它将返回 null。A null-conditional operator applies a member access, ?., or element access, ?[], operation to its operand only if that operand evaluates to non-null; otherwise, it returns null.

由于 PowerShell 允许 ? 作为变量名称的一部分,因此使用这些运算符需要变量名称的形式规范。Since PowerShell allows ? to be part of the variable name, formal specification of the variable name is required for using these operators. 因此,使用 {} 将变量名称括起来(如 ${a})或 ? 是变量名称 ${a?} 的一部分时需要形式规范。So it is required to use {} around the variable names like ${a} or when ? is part of the variable name ${a?}.

在下面的示例中,将返回 PropName 的值。In the following example, the value of PropName is returned.

$a = @{ PropName = 100 }
${a}?.PropName
100

下面的示例将返回 null,而不会尝试访问成员名称 PropNameThe following example will return null, without trying to access the member name PropName.

$a = $null
${a}?.PropName

同样,将返回元素的值。Similarly, the value of the element will be returned.

$a = 1..10
${a}?[0]
1

如果操作数为 null,则不会访问该元素,并返回 null。And when the operand is null, the element isn't accessed and null is returned.

$a = $null
${a}?[0]

备注

由于 PowerShell 允许 ? 作为变量名称的一部分,因此使用这些运算符需要变量名称的形式规范。Since PowerShell allows ? to be part of the variable name, formal specification of the variable name is required for using these operators. 因此,使用 {} 将变量名称括起来(如 ${a})或 ? 是变量名称 ${a?} 的一部分时需要形式规范。So it is required to use {} around the variable names like ${a} or when ? is part of the variable name ${a?}.

的变量名语法 ${<name>} 不应与 $() 子表达式运算符混淆。The variable name syntax of ${<name>} should not be confused with the $() subexpression operator. 有关详细信息,请参阅 about_Variables的变量名称部分。For more information, see Variable name section of about_Variables.

请参阅See also

about_Arithmetic_Operatorsabout_Arithmetic_Operators

about_Assignment_Operatorsabout_Assignment_Operators

about_Comparison_Operatorsabout_Comparison_Operators

about_Logical_Operatorsabout_Logical_Operators

about_Operator_Precedenceabout_Operator_Precedence

about_Type_Operatorsabout_Type_Operators

about_Pipeline_Chain_Operatorsabout_Pipeline_Chain_Operators

about_Splitabout_Split

about_Joinabout_Join

about_Redirectionabout_Redirection