Powershell: "-ErrorAction SilentlyContinue" ignored if used within try { }

Created on 24 Aug 2017  路  2Comments  路  Source: PowerShell/PowerShell

Steps to reproduce

function invoke-throw
{
        throw "hello"
}

try
{
        invoke-throw -erroraction silentlycontinue
}
finally
{
        "world"
}

Expected behavior

world

Actual behavior

world
hello
At C:\Users\slee\test\silentlycontinue.ps1:3 char:2
+     throw "hello"
+     ~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (hello:String) [], RuntimeException
    + FullyQualifiedErrorId : hello

Environment data

Name                           Value
----                           -----
PSVersion                      6.0.0-beta
PSEdition                      Core
GitCommitId                    v6.0.0-beta.5
OS                             Microsoft Windows 10.0.16261
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0
Resolution-Answered WG-Engine

Most helpful comment

@mklement0 ugh, you're right! my workaround has been to use a catch and ignore block

All 2 comments

As explained in Our Error Handling, Ourselves - time to fully understand and properly document PowerShell's error handling, the -ErrorAction common parameter acts only on _non-terminating_ errors.

You're triggering a (script)-_terminating_ error (with Throw), so -ErrorAction doesn't apply.
Because there is no Catch block, the error surfaces.

As explained in the linked post, confusingly, $ErrorActionPreference = 'SilentlyContinue' - i.e., use of the _preference variable_ rather than the _parameter_ - _does_ apply, so the following _is_ effective in silencing the error.

function invoke-throw
{
        throw "hello"
}

try
{
    $ErrorActionPreference = 'SilentlyContinue'    
    invoke-throw
}
finally
{
        "world"
}

Note: If you added a Catch block, then that block _by itself_ would silence the error message by default, irrespective of whether you used -ErrorAction SilentlyContinue or $ErrorActionPreference = 'SilentlyContinue'

@mklement0 ugh, you're right! my workaround has been to use a catch and ignore block

Was this page helpful?
0 / 5 - 0 ratings

Related issues

manofspirit picture manofspirit  路  3Comments

garegin16 picture garegin16  路  3Comments

HumanEquivalentUnit picture HumanEquivalentUnit  路  3Comments

andschwa picture andschwa  路  3Comments

rkeithhill picture rkeithhill  路  3Comments