$ LASTEXITCODE undefined after command

I'm going crazy, can someone explain to me why the value of $ lastexitcode is undefined?

Look at my simple attempt: if I run the dir command, I get the correct output, so $ LASTEXITCODE should be 0.

unfortunately if I try:

$LASTEXITCODE 

I have no return value. this is the same situation if I give a command like "diiiiir" or something similar that does not exist.

+4
source share
2 answers

$ LASTEXITCODE is set only by executable or batch files when they are returned. PowerShell commands can be checked with $. See here for more information.

+8
source

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" #Reset $LASTEXITCODE between runs while debugging 

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

0
source

Source: https://habr.com/ru/post/1482456/


All Articles