Quantcast
Channel: Windows PowerShell forum
Viewing all articles
Browse latest Browse all 21975

PowerShell Pipeline Fails Even With $ErrorActionPreference Set to "SilentlyContinue"

$
0
0

I am invoking PowerShell from C# and noticing that setting $ErrorActionPreference to "SilentlyContinue" seems to be getting ignored. When running in an interactive PowerShell session I get no error, but from C# I get an error about the command being invalid.

Here is the code:

        static void Main(string[] args)
        {
            Runspace runspace = RunspaceFactory.CreateRunspace();
            runspace.ApartmentState = System.Threading.ApartmentState.STA;
            runspace.ThreadOptions = PSThreadOptions.UseCurrentThread;
            runspace.Open();
            Pipeline pipeline = runspace.CreatePipeline();
            pipeline.Commands.AddScript(@"$ErrorActionPreference = ""SilentlyContinue""
                                           bogus-command
                                           Start-Sleep 10");
            pipeline.StateChanged += pipeline_StateChanged;
            pipeline.Input.Close();
            pipeline.InvokeAsync();
        }

        static void pipeline_StateChanged(object sender, PipelineStateEventArgs e)
        {
           if(e.PipelineStateInfo.State == PipelineState.Failed)
           {
             // Failure Occurred
           }
        }

The error reason is:

"The term 'bogus-command' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again."

The error is correct, but because of the $ErrorActionPreference I would expect it to be suppressed and continue on to remaining commands instead of failing the pipeline.


Viewing all articles
Browse latest Browse all 21975

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>