Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I need to store the output of a command line in a variable. How can I do this?

share|improve this question
Duplicate if How do I get the result of a command in a variable in windows? from Stack Overflow. – Cristian Ciupitu Jul 1 '14 at 16:56
up vote 5 down vote accepted

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:

Environment variable OUTPUT not defined
C:\>FOR /F "tokens=*" %a in ('test.cmd') do SET OUTPUT=%a

Should you want to use the FOR within a batch file, rather than command line, you need to change %a to %%a.

share|improve this answer
Your prompt doesn't have > for some reason which makes reading the commands more difficult since "C:\SET", for example, starts out looking like a path. – Dennis Williamson Mar 10 '11 at 15:22
@Dennis Edited. Sorry about that, should have used copy/paste. – jscott Mar 10 '11 at 15:42

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%.

share|improve this answer

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

share|improve this answer
Would you please expand your answer to explain how this stores anything in a variable? – jscott Mar 10 '11 at 13:48
i want to store output in variable .... and i try this method but it is failed ansd the output of command : commandline 1>fiel.txt what is "1" mean ??? and the file didn't creat – Mohammad AL-Rawabdeh Mar 10 '11 at 13:50

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.