Mohammad AL-Rawabdeh Asked: 2011-03-11 05:36:20 +0800 CST2011-03-11 05:36:20 +0800 CST 2011-03-11 05:36:20 +0800 CST Store output of Windows command in batch file 772 I need to store the output of a command line in a variable. How can I do this? windows command-line-interface batch-file 3 Answers Voted Best Answer jscott 2011-03-11T05:55:31+08:002011-03-11T05:55:31+08:00 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. jftuga 2011-03-11T06:14:50+08:002011-03-11T06:14:50+08:00 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%. Guido van Brakel 2011-03-11T05:44:02+08:002011-03-11T05:44:02+08:00 You can pipe the command into something like: command > somefile What you see above sends the output to a named file. If file does not exist, it creates one. Overwrites existing file And you can also do this: command >> somefile This appends the output to contents of a named file or creates a file if none exists See also here: Using command redirection operators
Provided a simple batch file
test.cmd
with the contents:You can set the output into a variable with the following command line:
Used on the command line like this:
Should you want to use the
FOR
within a batch file, rather than command line, you need to change%a
to%%a
.This is how I do this:
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%.
You can pipe the command into something like:
What you see above sends the output to a named file. If file does not exist, it creates one. Overwrites existing file And you can also do this:
This appends the output to contents of a named file or creates a file if none exists
See also here: Using command redirection operators