Reputation: 21
I am trying the below commands and want to get exit of my process(%ERRORLEVEL%)
. But it is returning previous(last)
executed exit code result of sample.exe
. I want to get exit code of current command. My requirement is to execute multiple commands in single line*(not batch script)*.
Command:
cmd /c sample.bat "test" > c:\ouput.log & echo %ERRORLEVEL% > c:\returnCode.log
I even tried using "setlocal enableDelayedExpansion" like below. Still It is not returning the exit code of current command
cmd /c setlocal enableDelayedExpansion & sample.bat "test" > c:\ouput.log & echo %ERRORLEVEL% > c:\returnCode.log
Please let me know the way to get current command's exit code.
Upvotes: 2
Views: 2422
Reputation: 67216
This should work:
cmd /V:ON /c sample.exe "test" > c:\ouput.log ^& echo !ERRORLEVEL! ^> c:\returnCode.log
/V:ON switch have the same effect of setlocal EnableDelayedExpansion
. For further details, type: cmd /?
EDIT: Small error fixed, the &
character must be escaped with ^
, otherwise, the echo !ERRORLEVEL!
command is not executed in the cmd /V:ON !!!
EDIT: Escaping the echo redirection via ^>
causes just that echo to be piped into the log. If you do not escape that, the entire command is piped there, i.e. including the stdout stream from "sample.exe".
Upvotes: 7
Reputation: 21
Thank for your response. I am able to get the exit code of current executed command with below command, only when I run through WMI class(Win32_Process). Using WMI client, I am executing the below command on Remote machine and it is working fine i.e. able to write exit code in Retrun.txt
Command: cmd /V:ON /c sample.bat "test" > c:\Output.txt & echo !ERRORLEVEL! > c:\Return.txt
But if I run the same command in command prompt of the same remote machine, it is printing "!ERRORLVEL!" in Return.txt instead of "sample.bat" exit code.
I am curious to know why it is not working if I run from Command prompt of the same machine locally.
Upvotes: 0
Reputation: 80023
cmd /c sample.exe "test" > c:\ouput.log & call echo %%ERRORLEVEL%% > c:\returnCode.log
Should work for you. See endless SO items related to delayedexpansion
Upvotes: 1