Skip to content
Incomplete sheet

This sheet is incomplete and could use some attention. Please submit code snippet suggestions as an issue or PR here.

Windows Batch

Scripting language for Windows Batch files.

Details To write comments, start the line with :: or REM. For in-line comments, use & :: or & REM.

Command-line argument handling

Action Code Details
Print _n_th parameter
echo %n
Check equality of _n_th parameter
if %n%==1 echo "Arg is 1!"

Variables

By default, variables are global!

For local declaration and usage of variables, encapsulate them in SETLOCAL and ENDLOCAL.

Action Code Details
Declare variable named name with value value
set name = value
Declare string variable
set msg = Hello world!
Declare empty string variable
set msg =
Declare numeric variable named name with value value
set /A name = value
Get value of variable named name
%name%
Environment variables are just variables.
Get PATH environment variable
%PATH%
Test of variable exists
set var1 = 2
if defined var1 echo "Variable var1 exists!"

Control flow

Action Code Details
If
if %status% == 200 echo OK
If-else
if %status% == 200 (echo OK) else (echo Error)
For-loop over range [a, b] with stepsize s
for /L %%var in (a,s,b) do echo %%var
Pause until user presses a key
pause
Pause until n seconds have elapsed or user presses a key
timeout n
End execution of script
exit /B
End execution of script
goto :eof

Number handling

Action Code Details
Add
set /A y = %x% + 1
Subtract
set /A y = %x% - 2
Multiply
set /A y = %x% * 2
Divide
set /A y = %x% / 2
Modulus
set /A y = x % 2

String handling

Action Code Details
Number of characters (length)
?
No standard function available
Concatenate strings
set w = world
set /a y = 2024
set msg = Hello %w% in %y%!
Test for empty string
[%msg%]==[]
Parse as integer
set /a count = %countstr%

Output

Action Code Details
Clear console
cls

Standard output

Action Code Details
Disable command prompts
@echo off
Print string
echo Hello world!

Filesystem handling

Action Code Details
Check if file exists
if exist C:\file.txt echo "File exists"