I'm going crazy, can someone explain me why the value of $lastexitcode is undefined?
look to my simple attempt: if I launch command dir, I get the correct output so $LASTEXITCODE must be 0.
unfortunately, if I try:
$LASTEXITCODE
I haven't any return value. it's the same situation if I give before an command like "diiiiir" or something similar that doesn't exist.
$LASTEXITCODE is only set by executables or batch files when they return. PowerShell commands can be checked with $?. See here for more information.
In particular $LASTEXITCODE is set by "Legacy" exectutables... it is equivalent to the old DOS/Windows %ERRORLEVEL% variable. Here is the best way to manage $LASTEXITCODE within PowerShell:
cmd /c "exit 0" #Reset $LASTEXITCODE between runs while debugging
A batch (.bat)/command (.cmd) file will set it when called from PowerShell:
exit /b <exitcode>
For example, create a command file called SetLASTEXITCODE.cmd with the following line:
exit /b 2
Then, call the command file from PowerShell:
cmd /c "SetLASTEXITCODE.cmd"
Output should be:
exit /b 2
Now test $LASTEXITCODE:
$LASTEXITCODE
Output is:
2
Note: on so called "Legacy" executables (also includes the old .com files), if the developer/programmer did not set the ERRORLEVEL from whatever programming language the exe was written in (usually via an API call), then ERRORLEVEL/LASTEXITCODE will not be set! I used to write these way back when in the early '80s and there was a distinction back then between internal commands like your 'dir' example which does not set ERRORLEVEL and external commands in (.com) or exe files - a long since forgotten detail.
One last example... modify the command file to include the following and repeat above test... it sets both ERRORLEVEL within command file and exits with %ERRORLEVEL% setting $LASTEXITCODE...
cmd /c "exit /b 2"
echo %ERRORLEVEL%
exit /b %ERRORLEVEL%
Have fun...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With