Powershell - Difference between $? and $LASTEXITCODE

To support me, you can subscribe to the channel, share and like the videos, disable your ad blocker or make a donation. Thank you!

Hello,

A new Powershell article on the difference between automatic $? variables and $LASTEXITCODE

$LASTEXITCODE contains the exit code of the last native program that was executed (0 indicating that everything went well, another value indicates a problem)

$? contains the pass/fail status of the last declaration (native program or Powershell): $true or $false

Demonstration with the following code:

# Select and execute all the code.
# Test native command OK
$null = ping localhost -n 1
"Command native OK `$? {0,15}" -f $?
"Command native OK `$LASTEXITCODE {0} " -f $LASTEXITCODE
# Test native command KO
$null = ping demo -n 1
"Command native KO `$? {0,16} " -f $?
"Command native KO `$LASTEXITCODE {0} " -f $LASTEXITCODE
# Powershell command test OK
$null = Test-Connection localhost -Count 1
"Powershell command OK `$? {0,15}" -f $?
"Powershell command OK `$LASTEXITCODE {0} " -f $LASTEXITCODE
# Test Powershell command KO
$null = Test-Connection demo -Count 1 -ErrorAction SilentlyContinue
"KO Powershell Command `$?{0,17} " -f $?
"Powershell Command KO `$LASTEXITCODE {0}" -f $LASTEXITCODE

We see appearing :

Powershell command OK  $LASTEXITCODE 1

$LASTEXITCODE has not been changed in the case of the Powershell command, the value 1 being the output code of ping demo -n 1.

So I can’t use $LASTEXITCODE to check the correct execution of a Powershell command, only native commands.

$? Responds correctly to native and Powershell commands.

Related links