[Solved] $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

$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

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


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

…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:


> 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


> 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
Respondent: Droj

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 $?


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

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

Respondent: Colonel Panic

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.

Respondent: Joey

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:

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

This inconsistency across hosts is discussed in this GitHub issue.

Respondent: mklement0

Solution #5:

Powershell 7.1

There is a new experimental feature to enable “sane” behaviour:

Enable-ExperimentalFeature PSNotApplyErrorActionToStderr

Unfortunately this feature cannot be enabled for the current scope only, it will be enabled for the whole user account (all users with argument -Scope AllUsers) and requires starting a new PS session before taking effect.

Now this sample code…

& cmd /c "echo Hello from standard error 1>&2" 2>&1
echo "`$LastExitCode=$LastExitCode and `$?=$?"
echo "`$Error.Count=$($Error.Count)"

…outputs what one would expect:

Hello from standard error
$LastExitCode=0 and $?=True
Respondent: zett42

Solution #6:

For me it was an issue with ErrorActionPreference.
When running from ISE I’ve set $ErrorActionPreference = “Stop” in the first lines and that was intercepting everything event with *>&1 added as parameters to the call.

So first I had this line:

& $exe $parameters *>&1

Which like I’ve said didn’t work because I had $ErrorActionPreference = “Stop” earlier in file (or it can be set globally in profile for user launching the script).

So I’ve tried to wrap it in Invoke-Expression to force ErrorAction:

Invoke-Expression -Command "& `"$exe`" $parameters *>&1" -ErrorAction Continue

And this doesn’t work either.

So I had to fallback to hack with temporary overriding ErrorActionPreference:

$old_error_action_preference = $ErrorActionPreference

    $ErrorActionPreference = "Continue"
    & $exe $parameters *>&1
    $ErrorActionPreference = $old_error_action_preference

Which is working for me.

And I’ve wrapped that into a function:


    Executes native executable in specified directory (if specified)
    and optionally overriding global $ErrorActionPreference.
function Start-NativeExecutable
    [CmdletBinding(SupportsShouldProcess = $true)]
        [Parameter (Mandatory = $true, Position = 0, ValueFromPipelinebyPropertyName=$True)]
        [string] $Path,

        [Parameter (Mandatory = $false, Position = 1, ValueFromPipelinebyPropertyName=$True)]
        [string] $Parameters,

        [Parameter (Mandatory = $false, Position = 2, ValueFromPipelinebyPropertyName=$True)]
        [string] $WorkingDirectory,

        [Parameter (Mandatory = $false, Position = 3, ValueFromPipelinebyPropertyName=$True)]
        [string] $GlobalErrorActionPreference,

        [Parameter (Mandatory = $false, Position = 4, ValueFromPipelinebyPropertyName=$True)]
        [switch] $RedirectAllOutput

    if ($WorkingDirectory)
        $old_work_dir = Resolve-Path .
        cd $WorkingDirectory

    if ($GlobalErrorActionPreference)
        $old_error_action_preference = $ErrorActionPreference
        $ErrorActionPreference = $GlobalErrorActionPreference

        Write-Verbose "& $Path $Parameters"

        if ($RedirectAllOutput)
            { & $Path $Parameters *>&1 }
            { & $Path $Parameters }
        if ($WorkingDirectory)
            { cd $old_work_dir }

        if ($GlobalErrorActionPreference)
            { $ErrorActionPreference = $old_error_action_preference }
Respondent: Michael Logutov

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.