Skip to main content

How to Store Command Output in a Variable in Batch Script

A fundamental task in any scripting language is to run a command, capture its output, and store that output in a variable for later use. You might need to get the current username, read a specific line from a file, or capture the status of a system utility. In batch scripting, there is no direct assignment operator for this; you cannot simply write SET MyVar = command.

Instead, the standard and most powerful method for capturing command output is to use the FOR /F command. This guide will teach you how to use FOR /F to capture single-line and multi-line output, and how to handle the common pitfalls you'll encounter along the way.

The Challenge: No Direct Output-to-Variable Assignment

Many scripting languages allow for a simple syntax like my_var = $(whoami). Batch scripting does not have this. An attempt to do this with redirection will fail: SET MyVar=<whoami.exe does not work. The command processor requires a specific structure to loop over the output that a command produces.

The Core Method: The FOR /F Command

The FOR /F loop is the designated workhorse for parsing text, whether from a file, a string, or, in this case, the output of a command.

The Syntax: FOR /F "options" %%V IN ('command-to-execute') DO SET "MyVariable=%%V"

  • FOR /F: Initiates the loop designed for parsing.
  • "options": Optional parsing parameters, like "delims=" to capture the entire line.
  • %%V: The loop variable that will hold the captured output.
  • ('command-to-execute'): This is the crucial part. The command you want to run must be enclosed in single quotes.
  • DO SET "MyVariable=%%V": This is the action to perform. It takes the value captured in %%V and assigns it to a standard variable.

Basic Example: Capturing a Single Line of Output

Let's start with a simple command, whoami, which prints the current user's name on a single line.

@ECHO OFF
SET "CurrentUser="

ECHO Capturing the output of the 'whoami' command...

FOR /F "delims=" %%A IN ('whoami') DO (
SET "CurrentUser=%%A"
)

ECHO.
ECHO The current user is: "%CurrentUser%"
note

The delims= option tells FOR /F not to split the line by spaces, ensuring the entire output line is captured.

Output:

Capturing the output of the 'whoami' command...

The current user is: "my-pc\adminuser"

How the FOR /F Method Works

When the command processor encounters this FOR /F loop, it:

  1. Executes the command inside the single quotes (whoami) in a new, hidden command prompt.
  2. Captures the text output that the command produces.
  3. The FOR /F loop then begins to iterate through that captured output, line by line.
  4. In our example, whoami only produces one line, so the loop runs exactly once.
  5. The DO block is executed, where the SET command assigns the content of that single line to the CurrentUser variable.

Handling Multi-Line Output

This is a critical concept. By default, if a command produces multiple lines of output, the FOR /F loop will iterate multiple times, and the SET command will overwrite the variable on each iteration. This means your variable will only hold the value of the last line of output.

The "Last Line Wins" Behavior

@ECHO OFF
SET "LastFile="
FOR /F "delims=" %%F IN ('DIR /B *.txt') DO (
SET "LastFile=%%F"
)
ECHO The last text file found was: %LastFile%

The Solution for Capturing All Lines

To concatenate all lines of output into a single variable, you must use Delayed Expansion.

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION

SET "FileList="
FOR /F "delims=" %%F IN ('DIR /B *.txt') DO (
SET "FileList=!FileList! %%F"
)

ECHO The complete list of files is:%FileList%

How it works: !FileList! accesses the current value of the variable inside the loop, allowing you to build the string across multiple iterations.

Common Pitfalls and How to Solve Them

Problem: The Command Produces No Output

If the command inside the single quotes produces no output, the FOR /F loop body will not execute at all. If your variable had a previous value, it will be retained, which can cause bugs.

Solution: Always initialize your variable to an empty state immediately before the loop.

SET "MyVar="
FOR /F ... DO ( SET "MyVar=%%A" )

This ensures that if the command fails or is empty, your variable will also be correctly empty.

Problem: The Command Contains Special Characters (|)

If your command includes a pipe or other special characters, the command processor will misinterpret it.

The Solution: You must escape the special character with a caret (^).

@ECHO OFF
SET "FileCount=0"
REM The pipe must be escaped with ^|
FOR /F %%C IN ('DIR /A-D /B ^| FIND /C /V ""') DO (
SET "FileCount=%%C"
)
ECHO There are %FileCount% files.

Practical Example: Getting the Date from WMIC

This script uses the robust WMIC command to get the current date and time in a locale-independent format and stores it in a variable. This is a perfect real-world use case.

@ECHO OFF
SET "Timestamp="

ECHO Getting a reliable timestamp from WMIC...

FOR /F "tokens=2 delims==" %%I IN ('WMIC OS GET LocalDateTime /VALUE') DO (
SET "Timestamp=%%I"
)

REM The timestamp from WMIC includes fractional seconds and timezone.
REM Let's just take the main part.
SET "Timestamp=%Timestamp:~0,14%"

ECHO The captured timestamp is: %Timestamp%

Conclusion

The FOR /F command is the standard and most powerful tool for capturing the output of another command into a variable.

Key takeaways for reliable scripting:

  • The core syntax is FOR /F %%V IN ('command') DO SET "MyVar=%%V".
  • The command to be executed must be in single quotes.
  • By default, the variable will only contain the last line of a multi-line output.
  • To capture all lines, you must use Delayed Expansion.
  • Escape special characters like the pipe with a caret (^|).
  • Always initialize your variable (SET "MyVar=") before the loop.