像ErrorActionPreference变量一样,ErrorAction参数的工作原理类似。高级功能和PowerShell中大多数内置cmdlet均支持ErrorAction参数。将非终止错误转换为终止错误,然后可以使用try / catch块进行处理,这很有用。
支持的值和示例,
继续-这是ErrorAction参数的默认值,并且将显示Error,并且将进一步执行Pipeline中列出的命令。
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
停止-错误消息将停止显示,并且管道中的执行命令也不会运行。下面的示例将没有输出。
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
忽略-忽略值与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
查询-当由于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"):
如果选择将显示一条错误消息是/ YestoAll以及暂停和暂停,也不会显示错误。
挂起-此值用于PowerShell工作流。暂停工作流以调查错误,然后可以恢复工作流。