How to use the ErrorActionPreference variable in PowerShell?


ErrorActionPreference variable in PowerShell is to control the non-terminating errors by converting them to terminating errors. Error handling depends upon which value you assign to $ErrorActionPreference variable.

The values are as below.

  • Continue − This is the default value of the variable and when the error occurs, an error is displayed in the PowerShell console, and the script continues the execution.

Get-WmiObject -Class Win32_Logicaldisk -ComputerName Nonexist
Write-Host "Hello World"

Output 

Get-WmiObject -Class Win32_Logicaldisk -ComputerName Nonexist
Write-Host "Hello World"
Get-WmiObject : The RPC server is unavailable.
At line:2 char:1
+ Get-WmiObject -Class Win32_Logicaldisk -ComputerName Nonexist
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Get-WmiObject],
COMException
+ FullyQualifiedErrorId :
GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObj
ectCommand
Hello World
  • Stop − Error will not be displayed in the console and further pipeline execution is stopped. In the below example, there will be no output.

$ErrorActionPreference = "Stop"
Get-WmiObject -Class Win32_Logicaldisk -ComputerName Nonexist
Write-Host "Hello World"
  • SilentlyContinue − Error output will not be displayed and the script executes the next commands in the pipeline.

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

Output −

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

Hello World
  • Inquire − It waits for user prompt if an error occurs and asks for continue. An error will be displayed.

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

Output 

If you press “Yes/Yes to All” then error output will be displayed and “Halt Command/Suspend” will not display an error.

  • Suspend − This value is used in the PowerShell workflow to suspend workflow for investigation purposes and then resume.

When you close the PowerShell session, the value of the $ErrorActionPreference will be set to default i.e. Continue.

Updated on: 27-May-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements