What is the difference between $ErrorActionPreference and $ErrorAction cmdlet in PowerShell ?


As we know $ErrorActionPreference and $ErrorAction both have the same functionality and both are used to handle terminating errors by converting Non-Terminating errors to Terminating errors. But when both the variables are used, we need to know which takes precedence.

$ErrorActionPreference variable is used at the start of the script while the $erroraction variable is a common parameter and used with the cmdlet. In some cases, we might need the script to be terminated as soon as an error occurs but inside the script, we have some cmdlets which need to be ignored or continued if the error occurs. In that situation, we -ErrorAction is important and it takes precedence.

Example

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

Output

Cannot find any service with service name 'ABC'.

In the above example, the script is terminated because the ABC service name doesn’t exist and because of it, the next commands can’t execute as the $ErrorActionPreference value is set to Stop. Once we add the -ErrorAction in the Get-Service command, it will take the precedence.

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

Output

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.

Once we add the -ErrorAction parameter with Continue value, execution moves to the next command as shown in the above output and stops when it can’t find process name “Chromesds” and can’t execute next command as -ErrorAction is not mentioned in that command.

Updated on: 03-Sep-2020

732 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements