Short description
介绍 PowerShell 支持的运算符。
Long description
运算符是可在命令或表达式中使用的语言元素。 PowerShell 支持多种类型的运算符来帮助你操作值。
Arithmetic Operators
使用算术运算符(+
、-
、*
、/
、%
)计算命令或表达式中的值。 使用这些运算符可以对值进行加减乘除,还可计算除法运算的余数(模数)。
加法运算符可连接元素。 乘法运算符返回每个元素的指定副本数。 可在任何实现它们的 .NET 类型上使用算术运算符,例如:Int
、String
、DateTime
、Hashtable
和数组。
按位运算符(-band
、-bor
、-bxor
、-bnot
、-shl
、-shr
)操作值中的位模式。
For more information, see about_Arithmetic_Operators.
Assignment Operators
使用赋值运算符(=
、+=
、-=
、*=
、/=
、%=
)向变量赋值、更改值或追加值。 可以将算术运算符与赋值结合起来,将算术运算的结果赋值给变量。
For more information, see about_Assignment_Operators.
Comparison Operators
使用比较运算符(-eq
、-ne
、-gt
、-lt
、-le
、-ge
)来比较值和测试条件。 例如,可以比较两个字符串值,确定它们是否相等。
比较运算符还包括用于在文本中查找或替换模式的运算符。 (-match
, , -notmatch
-replace
) 运算符使用正则表达式,并且 (-like
, -notlike
) 使用通配符,如*
和?
。
包含比较运算符确定测试值是否出现在引用集中(-in
、-notin
、-contains
、-notcontains
)。
类型比较运算符(-is
、-isnot
)确定对象是否为给定类型。
For more information, see about_Comparison_Operators.
Logical Operators
使用逻辑运算符(-and
、-or
、-xor
、-not
、!
)将条件语句连接到单个复杂条件中。 例如,可以使用逻辑 -and
运算符创建具有两个不同条件的对象筛选器。
For more information, see about_Logical_Operators.
Redirection Operators
使用重定向运算符(>
、>>
、2>
、2>>
和 2>&1
)将命令或表达式的输出发送到文本文件。 重定向运算符的工作方式类似于 Out-File
cmdlet(不含参数),但它们还允许将错误输出重定向到指定的文件。 也可使用 Tee-Object
cmdlet 重定向输出。
For more information, see about_Redirection
拆分运算符和联接运算符
-split
和 -join
运算符对子字符串进行划分和组合。
-split
运算符将字符串拆分为子字符串。
-join
运算符将多个字符串连接成一个字符串。
For more information, see about_Split and about_Join.
Type Operators
使用类型运算符(-is
、-isnot
、-as
)查找或更改对象的 .NET 类型。
For more information, see about_Type_Operators.
Unary Operators
使用一元 ++
和 --
运算符递增或递减值,使用 -
进行求反。 例如,若要将变量 $a
从 9
递增到 10
,请键入 $a++
。
For more information, see about_Arithmetic_Operators.
Special Operators
特殊运算符具有不适合任何其他运算符组的特定用例。 例如,通过特殊运算符,你可以运行命令、更改值的数据类型或从数组中检索元素。
分组运算符 ( )
与其他语言一样,(...)
用于重写表达式中的运算符优先级。 例如:(1 + 2) / 3
但是在 PowerShell 中,还有其他行为。
对结果表达式进行分组
(...)
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's run to completion with all output collected in memory before the results are sent through the pipeline.
如果在放入管道之前对表达式分组,还可确保后续的逐个对象处理不会干扰命令用于生成其输出的枚举。
对赋值语句进行分组
未分组的赋值语句不会输出值。 When grouping an assignment statement, the value of the assigned variable is passed through and can be used in larger expressions. For example:
PS> ($var = 1 + 2)
3
PS> ($var = 1 + 2) -eq 3
True
将语句包装在括号中会将其转换为输出 $var
的值的表达式。
此行为适用于所有赋值运算符,包括复合运算符(如 +=
)、递增运算符 (++
) 和递减运算符 (--
)。
但是,递增和递减运算的顺序取决于其位置。
PS> $i = 0
PS> (++$i) # prefix
1
PS> $i = 0
PS> ($i++) # postfix
0
PS> $i
1
在前缀情况下,$i
的值在输出之前递增。 在后缀情况下,$i
的值在输出之后递增。
还可以在条件语句的上下文中使用此技术,例如 if
语句。
if ($textFiles = Get-ChildItem *.txt) {
$textFiles.Count
}
在此示例中,如果没有文件匹配,Get-ChildItem
命令不会返回任何内容,并且不会向 $textFiles
进行任何赋值,这在布尔上下文中被视为 $false
。 If one or more FileInfo objects are assigned to $textFiles
, the conditional evaluates to $true
. 可以使用 $textFiles
语句正文中的 if
值。
Note
虽然此方法方便简洁,但它可能会导致赋值运算符 (=
) 和相等比较运算符 (-eq
) 之间出现混淆。
子表达式运算符 $( )
返回一个或多个语句的结果。 For a single result, returns a scalar. 对于多个结果,返回一个数组。 如果要在另一个表达式中使用某个表达式,请使用此方法。 例如,在字符串表达式中嵌入命令的结果。
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
数组表达式运算符 @( )
以数组形式返回一个或多个语句的结果。 结果始终为 0 个或多个对象的数组。
PS> $list = @(Get-Process | Select-Object -First 10; Get-Service | Select-Object -First 10 )
PS> $list.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
PS> $list.Count
20
PS> $list = @(Get-Service | Where-Object Status -EQ Starting )
PS> $list.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
PS> $list.Count
0
哈希表文本语法 @{}
与数组子表达式类似,此语法用于声明哈希表。 For more information, see about_Hash_Tables.
调用运算符 &
运行命令、脚本或脚本块。 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. 调用运算符在子作用域中执行。 For more about scopes, see about_Scopes. 可以使用它生成包含所需命令、参数和参数的字符串,然后像调用命令一样调用字符串。 创建的字符串必须与在命令行中键入的命令遵循相同的分析规则。 For more information, see about_Parsing.
此示例将命令存储在字符串中,并使用调用运算符执行该命令。
PS> $c = "Get-ExecutionPolicy"
PS> $c
Get-ExecutionPolicy
PS> & $c
AllSigned
调用运算符不会分析字符串。 这意味着在使用调用运算符时,不能在字符串中使用命令参数。
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.
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 a name of a cmdlet, function, script
file, or executable program. Check the spelling of the name, or if a path was
included, verify that the path is correct and try again.
PS> Invoke-Expression "1+1"
2
可以使用脚本的文件名执行脚本。 脚本文件的文件扩展名必须是 .ps1
才能执行。 路径包含空格的文件必须用引号括起来。 如果尝试执行带引号的路径,PowerShell 将显示带引号的字符串的内容,而不是运行脚本。 使用调用运算符可以执行包含文件名字符串的内容。
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!
For more about script blocks, see about_Script_Blocks.
后台运算符 &
在 PowerShell 作业中在后台运行它前面的管道。 此运算符的行为类似于 Unix 控件运算符与 (&
),该运算符在子Shell 中以作业的形式以异步方式在命令之前运行该命令。
此运算符的功能与 Start-Job
相同。 默认情况下,对于启动了并行任务的调用方,后台运算符启动其当前工作目录中的作业。 以下示例演示了后台作业运算符的基本用法。
Get-Process -Name pwsh &
此命令的功能与以下 Start-Job
用法相同:
Start-Job -ScriptBlock {Get-Process -Name pwsh}
与 Start-Job
一样,&
后台运算符会返回 Job
对象。 此对象可与 Receive-Job
和 Remove-Job
一起使用,就像使用 Start-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 控制运算符和 (&
) 一样。 这使你可以在 &
后台运算符之后调用其他命令。 以下示例演示了在 &
后台运算符之后调用其他命令的情况。
$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
这等效于以下脚本:
$job = Start-Job -ScriptBlock {Get-Process -Name pwsh}
Receive-Job $job -Wait
如果要运行多个命令,每个命令都在自己的后台进程中,但全部放在一行上,那么只需在每个命令之间和之后放置 &
即可。
Get-Process -Name pwsh & Get-Service -Name BITS & Get-CimInstance -ClassName Win32_ComputerSystem &
For more information on PowerShell jobs, see about_Jobs.
强制转换运算符 [ ]
将对象转换或限制为指定类型。 如果无法转换对象,PowerShell 会生成错误。
[datetime] '2/20/88' - [datetime] '1/20/88' -eq [timespan] '31'
A cast can also be performed when a variable is assigned to using cast notation.
逗号运算符 ,
作为二元运算符,逗号会创建数组或追加到要创建的数组。 在表达式模式下,作为一元运算符,逗号创建只有一个成员的数组。 将逗号放置在成员前面。
$myArray = 1,2,3
$SingleArray = ,1
Write-Output (,1)
Write-Output
需要参数,因此必须将表达式放在括号中。
点溯源运算符 .
在当前作用域内运行脚本,以便脚本创建的任何函数、别名和变量都添加到当前作用域,从而重写现有内容。 脚本声明的参数将成为变量。 没有给定值的参数将成为没有值的变量。 但是,将保留自动变量 $args
。
. C:\scripts\sample.ps1 1 2 -Also:3
Note
点溯源运算符后跟空格。 使用空格将点与表示当前目录的点 (.
) 符号区分开来。
在以下示例中,当前目录中的 Sample.ps1 脚本在当前作用域内运行。
. .\sample.ps1
格式运算符 -f
提供对 .NET 复合格式设置功能的访问权限。 A composite format string consists of fixed text intermixed with indexed placeholders, called format items. 这些格式项对应于列表中的对象。
每个格式项都采用下面的形式并包含以下组件:
{index[,alignment][:formatString]}
必须使用成对的大括号({
和 }
)。
格式设置操作产生的结果字符串由原始固定文本和列表中对象的字符串表示形式混和组成。 For more information, see Composite Formatting.
在运算符左侧输入复合格式字符串,以及要设置运算符右侧格式的对象。
"{0} {1,-10} {2:N}" -f 1,"hello",[Math]::PI
1 hello 3.14
可以使用“0”自定义说明符对数值进行零填充。
:
后面的零的数目指示将格式化字符串填充到的最大宽度。
"{0:00} {1:000} {2:000000}" -f 7, 24, 365
07 024 000365
如果需要保留格式化字符串中的大括号 ({}
),可通过使用两对大括号来对它们进行转义。
"{0} vs. {{0}}" -f 'foo'
foo vs. {0}
索引运算符 [ ]
从索引集合中选择对象,例如数组和哈希表。 数组索引从零开始,因此第一个对象被索引为 [0]
。 还可以使用负索引获取最后一个值。 哈希表按键值进行索引。
给定索引列表后,索引运算符将返回与这些索引对应的成员列表。
PS> $a = 1, 2, 3
PS> $a[0]
1
PS> $a[-1]
3
PS> $a[2, 1, 0]
3
2
1
(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...
当对象不是索引集合时,使用索引运算符访问第一个元素时将返回对象本身。 超出第一个元素的索引值会返回 $null
。
PS> (2)[0]
2
PS> (2)[-1]
2
PS> (2)[1] -eq $null
True
PS> (2)[0,0] -eq $null
True
管道运算符 |
将它前面的命令的输出发送(“管道传递”)到它后面的命令。 当输出包含多个对象(“集合”)时,管道运算符一次发送一个对象。
Get-Process | Get-Member
Get-Service | Where-Object {$_.StartType -eq 'Automatic'}
管道链运算符 &&
和 ||
根据左侧管道的成功,有条件地执行右侧管道。
# 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
For more information, see About_Pipeline_Chain_Operators.
范围运算符 ..
范围运算符可用于表示顺序整数或字符的数组。 范围运算符联接的值定义了范围的开始值和结束值。
Note
PowerShell 6 中添加了对字符范围的支持。
Number ranges
1..10
$max = 10
foreach ($a in 1..$max) {Write-Host $a}
还可以按相反顺序创建范围。
10..1
5..-5 | ForEach-Object {Write-Output $_}
范围的开始值和结束值可以是计算结果为整数或字符的任何表达式对。 范围的终结点必须可转换为有符号的 32 位整数([int32]
)。 较大的值会导致错误。 此外,如果在数组中捕获范围,则生成的数组的大小限制为 [int]::MaxValue - 56
。 这是 .NET 中数组的最大大小。
例如,可以将枚举的成员用于开始值和结束值。
PS> enum Food {
Apple
Banana = 3
Kiwi = 10
}
PS> [Food]::Apple..[Food]::Kiwi
0
1
2
3
4
5
6
7
8
9
10
Important
生成的范围不限于枚举的值, 而是表示提供的两个值之间的值范围。 不能使用范围运算符可靠地表示枚举的成员。
Character ranges
若要创建字符范围,请将字符用引号引起来。
PS> 'a'..'f'
a
b
c
d
e
f
PS> 'F'..'A'
F
E
D
C
B
A
如果将字符范围分配给字符串,则将其视为将字符数组分配给字符串。
PS> [string]$s = 'a'..'e'
$s
a b c d e
$a = 'a', 'b', 'c', 'd', 'e'
$a
a b c d e
数组中的字符联接成字符串。 字符由 $OFS
首选项变量的值分隔。 For more information, see about_Preference_Variables.
数组中的字符顺序由字符的 ASCII 值确定。 例如,c
和 X
的 ASCII 值分别为 99 和 88。 该范围将按相反的顺序显示。
PS> 'c'..'X'
c
b
a
`
_
^
]
\
[
Z
Y
X
成员访问运算符 .
访问对象的属性和方法。 成员名称可以是表达式。
$myProcess.PeakWorkingSet
(Get-Process powershell).Kill()
'OS', 'Platform' | ForEach-Object { $PSVersionTable. $_ }
从 PowerShell 3.0 开始,在对没有成员的列表集合对象使用运算符时,PowerShell 会自动枚举该集合中的项,并在其中每个项上使用运算符。 For more information, see about_Member-Access_Enumeration.
静态成员运算符 ::
调用 .NET 类的静态属性和方法。 若要查找对象的静态属性和方法,请使用 Get-Member
cmdlet 的 Static 参数。 成员名称可以是表达式。
[datetime]::Now
'MinValue', 'MaxValue' | ForEach-Object { [int]:: $_ }
三元运算符 ? <if-true> : <if-false>
在简单的条件情况下,可以使用三元运算符替代 if-else
语句。
For more information, see about_If.
Null 合并操作符 ??
如果 null 合并运算符 ??
不为 null,则它返回其左操作数的值。 否则,它将计算右操作数并返回其结果。 如果左操作数的计算结果为非 null,则 ??
运算符不会计算其右操作数。
$x = $null
$x ?? 100
100
在下面的示例中,不会计算右操作数。
[string] $todaysDate = '1/10/2020'
$todaysDate ?? (Get-Date).ToShortDateString()
1/10/2020
Null 合并赋值运算符 ??=
仅当左操作数的计算结果为 NULL 时,Null 合并赋值运算符 ??=
才会将其右操作数的值赋值给其左操作数。 如果左操作数的计算结果为非 null,则 ??=
运算符不会计算其右操作数。
$x = $null
$x ??= 100
$x
100
在下面的示例中,不会计算右操作数。
[string] $todaysDate = '1/10/2020'
$todaysDate ??= (Get-Date).ToShortDateString()
$todaysDate
1/10/2020
Null 条件运算符 ?.
和 ?[]
Note
在 PowerShell 7.1 中,此功能已从实验性功能转变为主要功能。
仅当操作数的计算结果为非 NULL 时,NULL 条件运算符才对其操作数应用成员访问 ?.
或元素访问 ?[]
操作;否则,它会返回 NULL。
由于 PowerShell 允许 ?
作为变量名称的一部分,因此使用这些运算符需要变量名称的形式规范。 必须使用大括号 ({}
) 将变量名称括起来(例如 ${a}
),或者当 ?
是变量名称 ${a?}
的一部分时使用大括号。
Note
不要将变量名称语法 ${<name>}
与 $()
子表达式运算符相混淆。 For more information, see Variable name section of about_Variables.
In the following example, the value of PropName is returned.
$a = @{ PropName = 100 }
${a}?.PropName
100
The following example returns null without trying to access the member name PropName.
$a = $null
${a}?.PropName
此示例将返回索引元素的值。
$a = 1..10
${a}?[0]
1
以下示例将返回 null,而不尝试访问索引元素。
$a = $null
${a}?[0]