Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I want to run a command and save its output and its exit code, in different files.

Here's what i am doing:

cmd.exe /C command 1> %TEMP%\output.log 2> %TEMP%\error.log && echo %ERRORLEVEL% > %TEMP%\status || echo %ERRORLEVEL% > %TEMP%\status

If i don't do output redirection (into %TEMP%\output.log and/or %TEMP%\error.log), then exit code is saved just fine. However, when i run the line as shown above more than once (just get back to previous line in command prompt and rerun it), i get 0 in %TEMP%\status regardless of the real exit code.

What am i missing? Or maybe there's a better way of doing this?

share|improve this question

1 Answer 1

up vote 4 down vote accepted

What you're doing won't save the exit code, as you're not capturing it. The simplest way is to run the command from inside a batch file. Redirect the output as normal and have the batch file save the ERRORLEVEL value to the second file.

share|improve this answer
    
What do you mean i am not capturing it? Should't %ERRORLEVEL% env contain exit code of last executed command in session? –  poncha Dec 2 '12 at 9:00
    
Yes, it does but any other operation will change it. In this instance the piping operations will themselves produce exit codes and that's what you will be getting, not the exit code from the command. Doing it in a batch file changes how the system does things. –  John Gardeniers Dec 2 '12 at 10:31
    
Got it ;) Thanks for the information! –  poncha Dec 2 '12 at 10:50

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.