Capture output command CMD

You can use FOR /F and go through some loops inside a batch file to capture the output:

@echo off
setlocal enabledelayedexpansion
set var=
for /f "tokens=* delims=" %%i in ('dir /tw /-c b.bat ^| findstr /B "[0-9]"') do set var=!var!^

%%i

echo %var%

It is especially important that there are two newlines between !var!^ and the %%i below.

Additionally you need to escape (again using ^) all characters inside the command line for FOR that have special meaning to the shell, such as the pipe in this instance.

The solution works by iterating over the output of the command and appending each line to the contents of var incrementally. To do that in a somewhat convenient manner the script enables delayed variable expansion (the !var! syntax).

Leave a Comment