Don't throw PowerShell exception on writes to stderr from external command Don't throw PowerShell exception on writes to stderr from external command powershell powershell

Don't throw PowerShell exception on writes to stderr from external command


tl;dr

The simplest workaround for the PowerShell ISE is the following (not needed in a regular console or in Visual Studio Code):

# Redirect stderr (2) to the success stream (1).# Doing so wraps stderr lines in [System.Management.Automation.ErrorRecord]# instances; calling .ToString() on them returns them as normal text.# CAVEAT: BE SURE THAT $ErrorActionPreference = 'Stop' is NOT IN EFFECT.git checkout devel 2>&1 | % ToString 

For other workarounds, including the ability to distinguish lines by stream of origin, see this answer.

However, you're better off switching to Visual Studio Code as your development environment, which solves the problem fundamentally - see below.

Two asides:

  • What you're seeing are non-terminating errors, not exceptions (while .NET exceptions underly PowerShell's error handling, they are always wrapped in [System.Management.Automation.ErrorRecord] instances and may or may not abort execution (terminating vs. non-terminating error)).

  • try / catch doesn't catch non-terminating errors, only terminating ones; while you could set $ErrorActionPreference = 'Stop' beforehand to promote non-terminating errors to terminating ones, execution of your program (in the ISE ) would be aborted on receiving the first stderr line.


You can avoid this problem if you limit your PowerShell use to:

These environments behaves as you would expect:

  • stderr (standard error) output is passed through to the display by default
  • stderr lines print just like regular lines.

Note:

  • In the context of remoting and background jobs, stderr output is still sent to PowerShell's error stream.

  • There are additional, host-independent problems with the use of 2> with external programs.

See this answer for a comprehensive overview of all problems.


How do I prevent native commands in a PowerShell script from throwing an exception on writes to stderr without completely blocking stderr?

You can try, with Git 2.16+, the option I mentioned in "PowerShell Capture Git Output"

 set GIT_REDIRECT_STDERR=2>&1

Check then if everything is written in stdout.


I usually redirrect ALL outputs to the same destination:

Invoke-Command -ScriptBlock {get-module} *>&1 

Or sometime I throw it into a file:

$scriptblock = {    get-module}Invoke-Command -ScriptBlock $scriptblock *>&1 >> file.txt