Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between $? and $LastExitCode in PowerShell

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.

like image 863
Colonel Panic Avatar asked May 19 '12 14:05

Colonel Panic


People also ask

What does $? Mean in PowerShell?

$? Contains the execution status of the last command. It contains True if the last command succeeded and False if it failed. For cmdlets and advanced functions that are run at multiple stages in a pipeline, for example in both process and end blocks, calling this.

How do I use $Lastexitcode in PowerShell?

Use the command Exit $LASTEXITCODE at the end of the powershell script to return the error codes from the powershell script. $LASTEXITCODE holds the last error code in the powershell script. It is in form of boolean values, with 0 for success and 1 for failure.

What does $() do in PowerShell?

$() is a special operator in PowerShell commonly known as a subexpression operator. It is used when we have to use one expression within some other expression. For instance, embedding the output of a command with some other expression.


1 Answers

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

like image 148
Joey Avatar answered Sep 18 '22 14:09

Joey