Home > Software design >  Powershell -ErrorAction SilentlyContinue not adding error to $Error variable
Powershell -ErrorAction SilentlyContinue not adding error to $Error variable

Time:01-09

I am hoping for a bit of help on an issue I'm having where once I add -ErrorAction SilentlyContinue to my command, no errors are written to the $Error variable. When I remove the ErrorAction, the command works perfectly fine and I can see the errors in the $Error variable but the errors are also printed to the console, which I don't want. Once I add the ErrorAction, the command still works but does not write any errors to the $Error variable.

Below is the function that contains the command.

function removebutton{
    Try{
        Write-Host "Please Wait..."
        Import-CSV $WPFfile_path.Text | foreach{Remove-DistributionGroupMember -Identity $WPFlist_email.Text -Member $_.email -Confirm:$false -ErrorAction SilentlyContinue}
        Write-Host("Completed Processing List")
        [System.Windows.MessageBox]::Show("Completed Processing List")       
            If ($error -ne $null) 
            {
            Write-Host -ForegroundColor Red ($Error | Select-Object Exception -ExpandProperty Exception | Out-String)
            [System.Windows.MessageBox]::Show(($Error | Select-Object Exception -ExpandProperty Exception | Out-String))
            }
            Else 
            {
            }
        Get-DistributiongroupMember $WPFlist_email.Text | Select-Object DisplayName, PrimarySMTPAddress | Out-GridView
        }
    Catch{
        [System.Windows.MessageBox]::Show(($Error[0]))
        }
        }

Any help will be greatly appreciated!

Kind regards, Dust

When I remove the ErrorAction, the command works perfectly fine and I can see the errors in the $Error variable but the errors are also printed to the console, which I don't want. Once I add the ErrorAction, the command still works but does not write any errors to the $Error variable.

CodePudding user response:

Note:

  • The following describes PowerShell's normal behavior.
  • As it turns out, an apparent bug in Remove-DistributionGroupMember prevents non-terminating errors from being recorded in $Error with -ErrorAction SilentlyContinue present, which - for reasons unknown - can be bypassed by using 2>$null to silence error output instead.

  • -ErrorAction SilentlyContinue continue does record non-terminating errors in the automatic $Error variable (it is only -ErrorAction Ignore that doesn't).

    • Do not use If ($Error -ne $null) to test if an error occurred in the most recent statement, given that $Error contains all errors that have occurred in the session so far.

      • As an aside: To test a value for $null, place it on the LHS of -eq / -ne, given that these operators act as filters with collections (arrays) as the LHS - see the docs.
    • Instead, use the automatic $? variable: if (-not $?)

      • Alternatively, you could run $Error.Clear() before the statement of interest, which would then allow you to use if ($Error.Count -gt 0), but that comes at the expense of wiping out the session-level history of errors.

      • The best option may be to use the common -ErrorVariable parameter, which allows you to collect a given call's non-terminating errors in a self-chosen variable (which must be specified without $; e.g., -ErrorVariable errs in order to collect errors in $errs); note that -ErrorAction SilentlyContinue (or redirection 2>$null) is still also needed to prevent error output.

  • However, non-terminating errors - which is what the common -ErrorAction parameter exclusively acts on - do not trigger the catch block of try ... catch ... finally statements - only terminating errors do.

    • However, you can promote non-terminating errors to terminating errors by using -ErrorAction Stop, causing them to triger the catch block too.
  • Note that, in a catch script block, you can more simply refer to the triggering error via the automatic $_ variable; that is, instead of $Error[0], you can use $_.


For a comprehensive overview of PowerShell's bewilderingly complex error handling, see GitHub docs issue #1583.

CodePudding user response:

Amazingly, replacing -ErrorAction SilentlyContinue with 2>$null resolved my issue. The errors are no longer written to console and only written to the $Error variable.

Thank you @mklement0 for your help! Much appreciated! I have bought you a coffee to say thanks!

  • Related