In Powershell, can I determine if my function was invoked with -ErrorAction SilentlyContinue?

StackOverflow https://stackoverflow.com/questions/23190700

  •  06-07-2023
  •  | 
  •  

Question

In my script, in order to determine if an error has even occurred, I need to do two extra remote queries. These take about 200 milliseconds and are pointless if the user is ignoring the error anyway. Is there a way to determine if I was called with -ErrorAction SilentlyContinue? Or do I have to add a separate switch to suppress the validation if the caller doesn't want it?

Was it helpful?

Solution

You can, if you want to, check the $ErrorActionPreference variable to see how errors should be handled.

You can read more about this and other preference variables if you do Get-Help about_preference_variables.

Edit 2014-04-22: Added an example on testing this behaviour

Here's an example of how you can test this:

function Test-Error
{
    [CmdletBinding()]
    PARAM()

    Write-Host "Error action preference is '$ErrorActionPreference'"
    Write-Error "This is a test error"
}

Test-Error
Test-Error -ErrorAction SilentlyContinue
Test-Error -ErrorAction Continue
Test-Error -ErrorAction Stop
Write-Host "We shouldn't get here, since last error action was 'Stop'"

This yields the following output:

Error action preference is 'Continue'
Test-Error : This is a test error
At line:12 char:5
+     Test-Error
+     ~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Test-Error

Error action preference is 'SilentlyContinue'
Error action preference is 'Continue'
Test-Error : This is a test error
At line:14 char:5
+     Test-Error -ErrorAction Continue
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Test-Error

Error action preference is 'Stop'
Test-Error : This is a test error
At line:15 char:5
+     Test-Error -ErrorAction Stop
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Test-Error
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top