I'm trying to use a Windows batch file to run a command, pipe its output to another command, and capture the exit status of the first command. But apparently, I can't do that, although I'll grant that Windows batch files are so arcane that I may have missed a technique. How can I both capture the exit status of a command and pipe its output?
It's the classic do_a_thing | tee logfile.txt
usage, but I want to be able to check whether do_a_thing
succeeded or not. After lots of fooling around, googling, and reading StackOverflow, I came up with the following:
setlocal enabledelayedexpansion
set rc=-1
( false & set rc=!errorlevel! & echo rc=!rc! ) | tee logfile.txt
echo %rc%
Which I had hoped would produce:
C:\>test.bat
C:\>setlocal enabledelayedexpansion
C:\>set rc=-1
C:\>(false & set rc=!errorlevel! & echo rc=!rc! ) | tee logfile.txt
rc=1
C:\>echo 1
1
But, alas, it did not:
C:\>test.bat
C:\>setlocal enabledelayedexpansion
C:\>set rc=-1
C:\>(false & set rc=!errorlevel! & echo rc=!rc! ) | tee logfile.txt
rc=!rc!
C:\>echo -1
-1
Removing the "| tee logfile.txt
" produces the expected value of !rc!
, but of course, it doesn't let me capture the log file.
C:\>test.bat
C:\>setlocal enabledelayedexpansion
C:\>set rc=-1
C:\>(false & set rc=!errorlevel! & echo rc=!rc! )
rc=1
C:\>echo 1
1