PowerShell 7 中引入了哪些新的空运算符?


PowerShell 7 版本引入了一些新的空运算符。它们如下所示。

  • 空合并运算符 - ??

  • 空条件赋值运算符 - ??=

  • 空条件成员访问运算符 - ?. 和 ?[]

a. 空合并运算符 - ??

空合并运算符 ?? 会评估左侧条件或操作数,如果它是空值,则评估右侧操作数;否则,提供左侧操作数的值。

例如,如果没有空合并运算符,我们将编写如下所示的脚本:

$Name = $null
if($Name -eq $null){"Name is Null"}
Else {"PowerShell"}

上面的相同条件可以用 ?? 运算符编写。

$name = $null
$name ?? "PowerShell"

输出:

PowerShell

因此,变量输出的左侧为空,因此评估右侧的值或表达式。

假设左侧操作数不为空,则将显示其值。

$name = "Hello"
$name ?? "PowerShell"
Hello

您还可以添加表达式:

$service = Get-Service abc -ErrorAction Ignore
$service ?? (Get-Service Spooler)

输出:

Status Name DisplayName
------ ---- -----------
Running Spooler Print Spooler

b. 空条件赋值运算符 - ??=

PowerShell 中的空条件赋值运算符 ??= 仅当左侧操作数的值为空时,才将右侧操作数的值赋给左侧操作数。如果左侧操作数为空,则此运算符不会评估右侧操作数。例如:

$serivce = $null
$service ??= (Get-Service Winrm)

输出:

$service
Status Name DisplayName
------ ---- -----------
Running Winrm Windows Remote Management (WS-Managem…

上面的命令类似于:

$service = $null
if($service -eq $null){$service = Get-Service Winrm}
$service
Status Name DisplayName
------ ---- -----------
Running Winrm Windows Remote Management (WS-Managem…

如果左侧运算符不为空,则值不会更改。

$val = "PowerShell"
$val ??= "Hello World"

输出:

$val
PowerShell

c. 空条件成员访问运算符 - ?. 和 ?[]

顾名思义,这两个运算符都用于访问对象的成员。这两个运算符都在 PS 7 版本中引入,并且仍在预览模式中,用于实验目的,因此并非每个人都能使用。

它类似于直接访问变量或对象的任何属性或成员,但是为什么我们需要它们呢?因为首先它会评估对象,如果它是空值,则它不会访问成员(属性或方法)。

由于我们使用这两个运算符来访问对象的属性或方法,因此我们需要将对象用 {} 括号括起来,然后才能使用运算符。例如:

$service = Get-Service WinRm
${Service}?.Status

输出:

Running

上面的示例也可以通过简单地访问属性来实现,但区别在于,如果服务名称不存在,则简单的命令会抛出错误,而如果服务名称为空,则此运算符不会抛出错误。例如:

$services = Get-Service ABC -ErrorAction ignore
$service.start()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $service.start()
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull

新的运算符不会给出任何输出,因为服务名称不存在。

${Service}?.Start()

更新于:2020年9月19日

178 次浏览

启动您的职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.