Specifically, $ LASTEXITCODE is set by exceptionutables Legacy ... this is equivalent to the old DOS / Windows variable% ERRORLEVEL%. Here is the best way to manage $ LASTEXITCODE in PowerShell:
cmd /c "exit 0"
The batch (.bat) / command (.cmd) file will install it when called from PowerShell:
exit /b <exitcode>
For example, create a batch file SetLASTEXITCODE.cmd with the following line:
exit /b 2
Then call the batch file from PowerShell:
cmd /c "SetLASTEXITCODE.cmd"
The conclusion should be:
exit /b 2
Now test $ LASTEXITCODE:
$LASTEXITCODE
Output:
2
Note: on so-called "obsolete" executables (also including old .com files), if the developer / programmer did not install ERRORLEVEL from any programming language in which exe was written (usually through an API call), then ERRORLEVEL / LASTEXITCODE will not be installed ! I used to write this way back, when in the beginning of the 80s, and then between internal commands , like your example 'dir', which does not install ERRORLEVEL and external commands in files (.com) or exe is a long forgotten detail.
One of the latest examples ... modify the batch file to include the following and repeat the above test ... it installs both ERRORLEVEL in the command file and exits with setting% ERRORLEVEL% $ LASTEXITCODE ...
cmd /c "exit /b 2" echo %ERRORLEVEL% exit /b %ERRORLEVEL%
Good luck ...
source share