How to set commands output as a variable in a batch file
Is it possible to set a statement's output of a batch file to a variable, for example:
findstr testing > %VARIABLE%
echo %VARIABLE%
FOR /F "tokens=* USEBACKQ" %%F IN (`command`) DO (
SET var=%%F
)
ECHO %var%
I always use the USEBACKQ so that if you have a string to insert or a long file name, you can use your double quotes without screwing up the command.
Now if your output will contain multiple lines, you can do this
SETLOCAL ENABLEDELAYEDEXPANSION
SET count=1
FOR /F "tokens=* USEBACKQ" %%F IN (`command`) DO (
SET var!count!=%%F
SET /a count=!count!+1
)
ECHO %var1%
ECHO %var2%
ECHO %var3%
ENDLOCAL
I found this thread on that there Interweb thing. Boils down to:
@echo off
setlocal enableextensions
for /f "tokens=*" %%a in (
'VER'
) do (
set myvar=%%a
)
echo/%%myvar%%=%myvar%
pause
endlocal
You can also redirect the output of a command to a temporary file, and then put the contents of that temporary file into your variable, likesuchashereby. It doesn't work with multiline input though.
cmd > tmpFile
set /p myvar= < tmpFile
del tmpFile
Credit to the thread on Tom's Hardware.