127

In PowerShell, what is the difference between $? and $LastExitCode?

I read about automatic variables, and it said:

$? Contains the execution status of the last operation. It contains TRUE if the last operation succeeded and FALSE if it failed.

$LastExitCode Contains the exit code of the last Windows-based program that was run.

In the definition of $? it doesn't explain what succeed and fail mean.


I ask because I presumed that $? is True if and only if $LastExitCode is 0, but I found a surprising counter-example: $LastExitCode=0 but $?=False in PowerShell. Redirecting stderr to stdout gives NativeCommandError.

0

1 Answer 1

141

$LastExitCode is the return code of native applications. $? just returns True or False depending on whether the last command (cmdlet or native) exited without error or not.

For cmdlets failure usually means an exception, for native applications it's a non-zero exit code:

PS> cmd /c "exit 5"
PS> $?
False
PS> cmd /c "exit 0"
PS> $?
True

Cancelling a cmdlet with Ctrl+C will also count as failure; for native applications it depends on what exit code they set.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks Joey. I myself thought $? meant non-zero exit code, but I've just found a surprising counterexample. See stackoverflow.com/questions/10666101/…
That's an interesting one. I would believe this to be a bug (because it behaves inconsistently between different PowerShell hosts).
And different cmdlets: @iex abcde@ for instance returns neither $?=False or $LastExitCode > 0
Invoke-Expression "rustc --version"; Write-Host $? $LastExitCode prints True 0 -- all good Invoke-Expression "rustc --sdasdasd"; Write-Host $? $LastExitCode prints True 1 -- oops
In addition rustc --sdasdasd; Write-Host $? $LastExitCode prints False 1 -- so there is a play of combination of factors depending on whether you use built-in commands and/or external commands.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.