Store output of Windows command in batch file
I need to store the output of a command line in a variable. How can I do this?
Solution 1:
Provided a simple batch file test.cmd
with the contents:
echo jscott
You can set the output into a variable with the following command line:
FOR /F "tokens=*" %a in ('test.cmd') do SET OUTPUT=%a
Used on the command line like this:
C:\>SET OUTPUT
Environment variable OUTPUT not defined
C:\>FOR /F "tokens=*" %a in ('test.cmd') do SET OUTPUT=%a
C:\>ECHO %OUTPUT%
jscott
Should you want to use the FOR
within a batch file, rather than command line, you need to change %a
to %%a
.
Solution 2:
This is how I do this:
vol c: > result.txt
set /p DATA=<result.txt
echo %DATA%
del result.txt
If result.txt has more than 1 line, only the top line of the file is used for %DATA%. You could also make result.txt into a variable itself, such as %OUTPUT%.