Windows – How to Store Output of Command in Batch File

batch-filecommand-line-interfacewindows

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

Best Answer

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.