powershellerror-handling

Powershell -ErrorAction SilentlyContinue not adding error to $Error variable


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.


Solution

  • Note:



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