如何在 PowerShell 中使用 ErrorAction 参数?


ErrorActionPreference 变量类似,ErrorAction 参数的工作方式也类似。ErrorAction 参数在高级函数和 PowerShell 中的大多数内置 cmdlet 中都受支持。它用于将非终止错误转换为终止错误,然后您可以使用 try/catch 块来处理它们。

支持的值和示例:

  • Continue - 这是 ErrorAction 参数的默认值,将显示错误,并且管道中列出的命令将继续执行。

Get-WmiObject -Class Win32_Logicaldisk -ComputerName Nonexist
-ErrorAction Continue
Write-Host "`nHello World" -BackgroundColor DarkGreen

输出

Get-WmiObject : The RPC server is unavailable.
At line:1 char:1
+ Get-WmiObject -Class Win32_Logicaldisk -ComputerName Nonexist -ErrorA ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Get-WmiObject], COMExcept ion
+ FullyQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands .GetWmiObjectCommand

Hello World
  • Stop - 错误消息将停止显示,并且管道中用于执行的命令将不会运行。以下示例将没有输出。

示例

PS C:\WINDOWS\system32>>> Get-WmiObject -Class Win32_Logicaldisk -ComputerName
Nonexist -ErrorAction Stop
Write-Host "`nHello World" -BackgroundColor DarkGreen
  • SilentlyContinue - 不会显示错误消息,脚本将执行管道命令。

示例

Get-WmiObject -Class Win32_Logicaldisk -ComputerName Nonexist -
ErrorAction SilentlyContinue
Write-Host "`nHello World" -BackgroundColor DarkGreen

输出

PS C:\WINDOWS\system32>>> Get-WmiObject -Class Win32_Logicaldisk -ComputerName Nonexist -ErrorAction SilentlyContinue
Write-Host "`nHello World" -BackgroundColor DarkGreen

Hello World
  • Ignore - Ignore 值与 Silentlycontinue 相同,除了错误输出不会存储到 $Error 变量中。

Get-WmiObject -Class Win32_Logicaldisk -ComputerName
Nonexist -ErrorAction Ignore
Write-Host "`nHello World" -BackgroundColor DarkGreen

Hello World

现在检查错误变量。您在以下示例中可以看到,它不包含任何错误数据,而在 SilentlyContinue 值中,它存储了错误输出。

PS C:\WINDOWS\system32>>> $Error
  • Inquire - 当由于 cmdlet 发生错误时,此选项会为用户提供以下选择并提示采取适当的操作。

Get-WmiObject -Class Win32_Logicaldisk -ComputerName Nonexist -
ErrorAction Inquire
Write-Host "`nHello World" -BackgroundColor DarkGreen

输出

Confirm
The RPC server is unavailable.
[Y] Yes [A] Yes to All [H] Halt Command [S] Suspend [?] Help (default is "
Y"):

如果您选择 Yes/YestoAll,则会显示错误消息,对于 Haltsuspend,则不会显示错误。

  • Suspend - 此值用于 PowerShell 工作流。工作流将暂停以调查错误,然后可以恢复工作流。

更新于: 2020年5月27日

9K+ 次浏览

启动您的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.