$LastExitCode=0, but $?=False in PowerShell. Redirecting stderr to stdout gives NativeCommandError

Why does PowerShell show the surprising behaviour in the second example below?

First, an example of sane behaviour:

PS C:\> & cmd /c "echo Hello from standard error 1>&2"; echo "`$LastExitCode=$LastExitCode and `$?=$?"
Hello from standard error
$LastExitCode=0 and $?=True

No surprises. I print a message to standard error (using cmd's echo). I inspect the variables $? and $LastExitCode. They equal to True and 0 respectively, as expected.

However, if I ask PowerShell to redirect standard error to standard output over the first command, I get a NativeCommandError:

PS C:\> & cmd /c "echo Hello from standard error 1>&2" 2>&1; echo "`$LastExitCode=$LastExitCode and `$?=$?"
cmd.exe : Hello from standard error
At line:1 char:4
+ cmd <<<<  /c "echo Hello from standard error 1>&2" 2>&1; echo "`$LastExitCode=$LastExitCode and `$?=$?"
    + CategoryInfo          : NotSpecified: (Hello from standard error :String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

$LastExitCode=0 and $?=False

My first question, why the NativeCommandError?

Secondly, why is $? False when cmd ran successfully and $LastExitCode is 0? PowerShell's documentation about automatic variables doesn't explicitly define $?. I always supposed it is True if and only if $LastExitCode is 0, but my example contradicts that.


Here's how I came across this behaviour in the real-world (simplified). It really is FUBAR. I was calling one PowerShell script from another. The inner script:

cmd /c "echo Hello from standard error 1>&2"
if (! $?)
{
    echo "Job failed. Sending email.."
    exit 1
}
# Do something else

Running this simply as .\job.ps1, it works fine, and no email is sent. However, I was calling it from another PowerShell script, logging to a file .\job.ps1 2>&1 > log.txt. In this case, an email is sent! What you do outside the script with the error stream affects the internal behaviour of the script. Observing a phenomenon changes the outcome. This feels like quantum physics rather than scripting!

[Interestingly: .\job.ps1 2>&1 may or not blow up depending on where you run it]


Solution 1:

(I am using PowerShell v2.)

The '$?' variable is documented in about_Automatic_Variables:

$?
  Contains the execution status of the last operation

This is referring to the most recent PowerShell operation, as opposed to the last external command, which is what you get in $LastExitCode.

In your example, $LastExitCode is 0, because the last external command was cmd, which was successful in echoing some text. But the 2>&1 causes messages to stderr to be converted to error records in the output stream, which tells PowerShell that there was an error during the last operation, causing $? to be False.

To illustrate this a bit more, consider this:

> java -jar foo; $?; $LastExitCode
Unable to access jarfile foo
False
1

$LastExitCode is 1, because that was the exit code of java.exe. $? is False, because the very last thing the shell did failed.

But if all I do is switch them around:

> java -jar foo; $LastExitCode; $?
Unable to access jarfile foo
1
True

... then $? is True, because the last thing the shell did was print $LastExitCode to the host, which was successful.

Finally:

> &{ java -jar foo }; $?; $LastExitCode
Unable to access jarfile foo
True
1

...which seems a bit counter-intuitive, but $? is True now, because the execution of the script block was successful, even if the command run inside of it was not.


Returning to the 2>&1 redirect.... that causes an error record to go in the output stream, which is what gives that long-winded blob about the NativeCommandError. The shell is dumping the whole error record.

This can be especially annoying when all you want to do is pipe stderr and stdout together so they can be combined in a log file or something. Who wants PowerShell butting in to their log file??? If I do ant build 2>&1 >build.log, then any errors that go to stderr have PowerShell's nosey $0.02 tacked on, instead of getting clean error messages in my log file.

But, the output stream is not a text stream! Redirects are just another syntax for the object pipeline. The error records are objects, so all you have to do is convert the objects on that stream to strings before redirecting:

From:

> cmd /c "echo Hello from standard error 1>&2" 2>&1
cmd.exe : Hello from standard error
At line:1 char:4
+ cmd &2" 2>&1
    + CategoryInfo          : NotSpecified: (Hello from standard error :String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

To:

> cmd /c "echo Hello from standard error 1>&2" 2>&1 | %{ "$_" }
Hello from standard error

...and with a redirect to a file:

> cmd /c "echo Hello from standard error 1>&2" 2>&1 | %{ "$_" } | tee out.txt
Hello from standard error

...or just:

> cmd /c "echo Hello from standard error 1>&2" 2>&1 | %{ "$_" } >out.txt

Solution 2:

This bug is an unforeseen consequence of PowerShell's prescriptive design for error handling, so most likely it will never be fixed. If your script plays only with other PowerShell scripts, you're safe. However if your script interacts with applications from the big wide world, this bug may bite.

PS> nslookup microsoft.com 2>&1 ; echo $?

False

Gotcha! Still, after some painful scratching, you'll never forget the lesson.

Use ($LastExitCode -eq 0) instead of $?

Solution 3:

(Note: This is mostly speculation; I rarely use many native commands in PowerShell and others probably know more about PowerShell internals than me)

I guess you found a discrepancy in the PowerShell console host.

  1. If PowerShell picks up stuff on the standard error stream it will assume an error and throw a NativeCommandError.
  2. PowerShell can only pick this up if it monitors the standard error stream.
  3. PowerShell ISE has to monitor it, because it is no console application and thus a native console application has no console to write to. This is why in the PowerShell ISE this fails regardless of the 2>&1 redirection operator.
  4. The console host will monitor the standard error stream if you use the 2>&1 redirection operator because output on the standard error stream has to be redirected and thus read.

My guess here is that the console PowerShell host is lazy and just hands native console commands the console if it doesn't need to do any processing on their output.

I would really believe this to be a bug, because PowerShell behaves differently depending on the host application.

Solution 4:

Update: Preview versions of v7.2 now contains an experimental feature that fixes the problems below - see this answer; note, however, that experimental features aren't guaranteed to become official features.


A summary of the problems as of v7.1:

The PowerShell engine still has bugs with respect to 2> redirections applied to external-program calls:

The root cause is that using 2> causes the stderr (standard error) output to be routed via PowerShell's error stream (see about_Redirection), which has the following undesired consequences:

  • If $ErrorActionPreference = 'Stop' happens to be in effect, using 2> unexpectedly triggers a script-terminating error, i.e. aborts the script (even in the form 2>$null, where the intent is clearly to ignore stderr lines). See this GitHub issue.

    • Workaround: (Temporarily) set $ErrorActionPreference = 'Continue'
  • Since 2> currently touches the error stream, $?, the automatic success-status variable is invariably set to $False if at least one stderr line was emitted, and then no longer reflects the true success status of the command. See this GitHub issue.

    • Workaround, as recommended in your answer: only ever use $LASTEXITCODE -eq 0 to test for success after calls to external programs.
  • With 2>, stderr lines are unexpectedly recorded in the automatic $Error variable (the variable that keeps a log of all errors that occurred in the session) - even if you use 2>$null. See this GitHub issue.

    • Workaround: Short of keeping track how many error records were added and removing them with $Error.RemoveAt() one by one, there is none.

Generally, unfortunately, some PowerShell hosts by default route stderr output from external programs via PowerShell's error stream, i.e. treat it as error output, which is inappropriate, because many external programs use stderr also for status information, or more generally, for anything that is not data (git being a prime example): Not every stderr line can be assumed to represent an error, and the presence of stderr output does not imply failure.

Affected hosts:

  • The obsolescent Windows PowerShell ISE and possibly other, older GUI-based IDEs other than Visual Studio Code.

  • When executing external programs via PowerShell remoting or in a background job (these two invocation mechanisms share the same infrastructure and use the ServerRemoteHost host that ships with PowerShell).

Hosts that DO behave as expected in non-remoting, non-background invocations (they pass stderr lines through to the display and print them normally):

  • Terminals (consoles), including Windows Terminal.

  • Visual Studio Code with the PowerShell extension; this cross-platform editor (IDE) is meant to supersede the Windows PowerShell ISE.

This inconsistency across hosts is discussed in this GitHub issue.