PowerShell 中 $ErrorActionPreference 和 $ErrorAction cmdlet 有什么区别?


我们知道 **$ErrorActionPreference** 和 **$ErrorAction** 都有相同的功能,并且都用于通过将 **非终止** 错误转换为 **终止** 错误来处理终止错误。但是,当这两个变量都使用时,我们需要知道哪个优先。

**$ErrorActionPreference** 变量用于脚本的开头,而 **$erroraction** 变量是一个通用参数,并与 cmdlet 一起使用。在某些情况下,我们可能需要脚本在发生错误时立即终止,但在脚本内部,我们有一些 cmdlet 需要忽略或继续执行,如果发生错误。在这种情况下,**-ErrorAction** 非常重要,并且它具有优先级。

示例

$ErrorActionPreference = "Stop"
try{
   Get-Service -Name ABC
   Get-Process powershell
   Get-Process chromesds
   Get-Service Spooler
}
catch{
   $_.Exception.Message
}

输出

Cannot find any service with service name 'ABC'.

在上面的示例中,脚本被终止,因为服务名称 **ABC** 不存在,因此,由于 **$ErrorActionPreference** 值设置为 **Stop**,因此后续命令无法执行。一旦我们在 **Get-Service** 命令中添加了 **-ErrorAction**,它将具有优先级。

$ErrorActionPreference = "Stop"
try{
   Get-Service -Name ABC -ErrorAction Continue
   Get-Process powershell
   Get-Process chromesds
   Get-Service Spooler
}
catch{
   $_.Exception.Message
}

输出

Line |
   4 |       Get-Service -Name ABC -ErrorAction Continue
     |       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Cannot find any service with service name 'ABC'.
NPM(K)    PM(M)    WS(M)    CPU(s)    Id    SI    ProcessName
------    -----    -----    ------    --    --    -----------
43       234.39    11.33    49.17    7668    1    powershell
Cannot find a process with the name "chromesds". Verify the process name and call
the cmdlet again.

一旦我们在带有 Continue 值的 -ErrorAction 参数中添加了它,执行将移动到下一条命令,如上面的输出所示,并在找不到进程名称“Chromesds”时停止,并且无法执行下一条命令,因为在该命令中没有提到 -ErrorAction。

更新于: 2020年9月3日

820 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.