user1408899
user1408899

Reputation: 21

Redirecting output from a batch file, INCLUDING the commands

I have a batch file that executes a series of commands. As each one executes, it returns either a "success" or "fail" message. Its simple enough to redirect the output from each of these using the >> and send it to a file, but without the associated command the output is useless.

(Batch File)

Command "D21" >> Myfile.txt
Command "D22" >> Myfile.txt
Command "D23" >> Myfile.txt
Command "D24" >> Myfile.txt

(Output file: Myfile.txt)

Fail
Succeed
Fail
Succeed

What I would like to do is also send the command that was executed to that file so it might look like this...

(Desired output file: Myfile.txt)

Command "D21" Fail
Command "D22" Fail
Command "D23" Succeed
Command "D24" Succeed

Any thoughts on how I could accomplish this with a minimum of effort?

Upvotes: 2

Views: 7595

Answers (3)

Kevin Fegan
Kevin Fegan

Reputation: 1290

There are two ways to do this. The first is a little "cryptic" but it gets it done in a one-line command:

for %%f in ("Command "D21"" "Command "D22"" "Command "D23"" "Command "D24"") do for /F "usebackq delims=" %%g in (`%%~f`) do echo %%~f %%g >> MyFile.txt

This should work just fine. It's just a little cubmersome to add more Command "xxx"'s.

The second way is to use a "subroutine" to handle the work:

@echo off

call :work Command "D21"
call :work Command "D22"
call :work Command "D23"
call :work Command "D24"
goto :EOF



:work
for /F "usebackq delims=" %%g in (`%*`) do echo %* %%g
goto :EOF

Upvotes: 0

panda-34
panda-34

Reputation: 4209

This is the way to put command and response on the same line

@echo off
for /f "skip=6 delims=" %%i in (%~dpnx0) do (
    <nul set /p =%%i >> MyFile.txt
    %%i >> MyFile.txt
)
goto :eof
Command "D21"
Command "D22"
Command "D23"
Command "D24"

Upvotes: 0

dbenham
dbenham

Reputation: 130819

I presume you want to selectively redirect echoed commands and output within the batch, and not the whole batch.

@echo off
echo before not echoed, not captured
call :echoCommands >myFile.txt
echo after not echoed, not captured
exit /b

:echoCommands
echo on
Command "D21"
Command "D22"
Command "D23"
Command "D24"
@echo off
exit /b

If you want to capture the entire batch file, then simply remove the redirection from the script, don't turn echo off, and redirect when you call the batch script.

myScript >myFile.txt

If you want to capture the entire file output with commands, and you really want to redirect within the script, then something like

@if "%~1" neq "_GO_" (
  >myFile.txt call "%~f0" _GO_ %*
  exit /b
)
@echo on
Command "D21"
Command "D22"
Command "D23"
Command "D24"

In all of the solutions above, each command will be printed on one line, and the output will follow on the subsequent line(s).

Upvotes: 2

Related Questions