Windows Batch Scripting Fundamentals

Variable Declaration and Usage

Defining Variables

Variables are typically declared using the set command, and their values usually do not require quotation marks.

set name=John Doe

When quotes are used, the variable includes them. To remove these, use %~variable syntax. For example, set var="value" stores the quotes, so referencing it requires %~var to strip them.

Referencing Variables

Handling Quotation in Variable References

If a variable's value contains spaces or special characters like &, |, >, <, or ^, it should be quoted during reference.

set file_path=C:\My Documents\test.txt
:: Incorrect: 'Documents' will be interpreted as a separate command
 copy %file_path% D:\Backup\
:: Correct: pass the path as a whole
 copy "%file_path%" D:\Backup\

In conditional checks (e.g., if, exist) involving file or directory existence or string comparisons, always quote variables to prevent misinterpretation due to spaces.

set target=C:\Program Files\app.exe
:: Incorrect: 'Program' and 'Files' split into tokens
if exist %target% (
    echo Exists
) else (
    echo Not found
)
:: Correct: treat the entire path as one unit
if exist "%target%" (
    echo Exists
) else (
    echo Not found
)

Delayed Variable Expansion

By default, batch scripts resolve all variables before execution. However, within blocks like if or for, newly defined variables are evaluated at runtime. This can cause issues when referencing such variables.

Enable delayed expansion via setlocal enabledelayedexpansion and use !variable! instead of %variable% to access updated values.

Without delayed expansion:

@echo off
if 1==1 (
    set my_var=Hello
    echo Value: %my_var%  :: Outputs empty because of immediate expansion
)
pause

With delayed expansion:

@echo off
setlocal enabledelayedexpansion
if 1==1 (
    set my_var=Hello
    echo Value: !my_var!  :: Correctly outputs 'Hello'
)
endlocal
pause

Input and Output

Input

Basic Input: set /p

Use set /p to prompt users for input and store it in a variable.

Syntax: set /p variable=prompt

Example:

@echo off
set /p username=Enter username: 
 echo You entered: %username%
pause

Limited Options: choice

The choice command lets users select from predefined options (Windows XP+).

Syntax: choice /c choices /n /m message

Example:

@echo off
choice /c YN /n /m "Continue? (Y/N)"
if errorlevel 2 (
    echo You chose N, exiting...
    exit /b
)
if errorlevel 1 (
    echo You chose Y, continuing...
)
pause

Parameters:

  • /c YN: Available choices are Y and N;
  • /n: Suppresses display of choice list;
  • /m: Custom prompt message;
  • errorlevel: Index of selected option (starting from 1).

Output

Commands like echo send text or varible values to the screen.

Basic Output: echo

Use echo to print static text or variable contents.

echo Hello World
set name=Alice
echo Name: %name%

Control echoing with @echo off to suppress command display.

@echo off
:: No commands shown during script execution
echo Silent execution...

Output Redirection

Use > (overwrite) or >> (append) to write output to files.

echo Hello > output.txt
:: Creates or clears output.txt

echo World >> output.txt
:: Appends to existing file

To insert a newline, use echo. or echo. followed by a newline.

echo Hello > output.txt
echo. >> output.txt
echo World >> output.txt

Redirect command results:

dir C:\ >> dir_list.txt

Reading Multi-line Input (Advanced)

To capture multi-line user input, combine loops with set /p:

@echo off
setlocal enabledelayedexpansion
set input_lines=
set count=0
:input_loop
set /p line=Line !count!: 
if "!line!"=="" goto :end_input
set input_lines=!input_lines!!line!
set /a count+=1
goto :input_loop
:end_input
echo Your input: !input_lines!
pause

File I/O Operations

Batch scripts support reading and writing files through redirection and for /f loops.

Reading File Contents

Single Line:

Read the first line using set /p with input redirection:

@echo off
set /p first_line=<C:\test.txt
echo First line: !first_line!
pause

All Lines:

Loop through each line using for /f:

@echo off
for /f "delims=" %%i in (C:\test.txt) do (
    echo Line: %%i
)
pause

delims= disables tokenization, preserving whitespace.

Writing to Files

Overwrite or Append:

echo Line 1 > C:\output.txt
echo Line 2 >> C:\output.txt

Multiple Lines:

Use block redirection:

(
    echo Line 1
    echo Line 2
    echo Line 3
) > C:\multi_line.txt

Summary

Core operations in batch scripting:

  • Input: Use set /p for user input, choice for selections;
  • Output: Use echo for text/variables, >/>> for file redirection;
  • File I/O: Read single lines with set /p <file, read multiple lines with for /f, write with >/>>.

Tags: Windows batch Scripting Variables input-output

Posted on Sun, 02 Aug 2026 16:54:49 +0000 by EvilWalrus