Site Overlay

Batch script cheat sheet

Batch scripts are possibly the most complicated and difficult things to create. So here's a small collection of snippets that I've used before, hopefully this can help someone else too.


:: Name       Random file picker
:: Purpose    Open a random file in this directory.
:: Author     jjv360
:: Revision   5 January 2020 - Initial version
              12 March 2020  - Whitespace fix

@echo off
setlocal EnableDelayedExpansion
title Random file picker

Header comment: Comments can also start with ::, which is useful for creating nice headers. They cause problems inside blocks though, so best not to use them anywhere else.

echo off is also a good thing to have at the start of your script, it prevents each line from being printed out during execution. Putting @ in front of a line prevents that line from being printed out as well.

Enabling delayed expansion is also a very useful thing to have, and using setlocal will ensure any variables you change will not be persisted when the script ends.

rem This is a comment

Comments: A single line comment starts with rem.

echo off
echo Hello world!

Writing text out: Anything after echo is printed to the screen, except for echo off which disables command echoing, and echo. which prints a blank line.

title My Terminal

Change the window title: Allows changing the title of the terminal window.


Clear the screen: This command clears all output from the terminal window.

color 02
echo This text is green!

Set text color: Use the color command to set the background and foreground color of any future printed text. See here for a list of colors.


set Name=Josh
echo Hello, %Name%.

Create and use variables: You can create variables with the set command. Note, lack of spaces around the = is important.

You can use variables anywhere by using the format %MyVariableName%.

cd /D "%USERPROFILE%\Desktop"

Change working directory: Use the /D flag to make sure the working drive is also changed.

setlocal EnableDelayedExpansion

Allow variables inside loops: In any code block like FOR ... DO ( ... ) the entire block's variables are expanded only once. This means if you set a variable in there, you can't use it from inside the block.

Delayed expansion allows you to expand variables only when they're needed, by using !MyVar! instead of %MyVar%.

Note: Using setlocal means when your script ends, all variables modified after that (including working directory changes) are not stored.

set /a Num=3 * 20
echo 3 * 20 = %Num%

Do maths: Using set /a, you can do simple maths. Batch scripts are only capable of doing calculations using 32-bit integers.

rem Pick a number between 5 and 10
set /a Num=%random% %% 5 + 5
echo Picked number: %Num%

Random numbers: The built-in variable %random% generates a random number between 0 and 32768 (exclusive) every time you use it.

You can also use some maths with the (escaped) modulus operator %% to pick a random number of your choosing.

set /p Name="Enter your name: "
echo Hello, %Name%

Ask for user input: You can use set /p to ask the user to set a variable.

SET cmd="wmic ComputerSystem get name"
FOR /F "skip=1" %%A IN ('%cmd%') DO (
  set ComputerName=%%A
  goto leaveSystemName

echo Computer name is %ComputerName%

Parsing output from commands: You can use a FOR /F loop to process each line of output from a command.

You can also use a goto to leave the loop early.

Remember to use setlocal EnableDelayedExpansion if you need to set and use a variabe inside the loop.

See here for more for loop options.

set Txt=My long text string.
echo Full string: %Txt%
echo First 3 chars: %Txt:~0,3%
echo Last 3 chars: %Txt:~-3%
echo Chars 3 to 6: %Txt:~3,6%
echo Chars 3 to last 3: %Txt:~3,-3%

Substrings: You can use substrings with the %VarName:~From,To% format. Negative indexes can be used to get an index from the end of the string. If To is missing, it takes until the end of the string.

set var=One two three two six
echo %var:two=four%

set var=One two three two six
set vFind=two
set vReplace=four
echo %var:!vFind!=!vReplace!%

String substitution: You can use %Var:Find=Replace% to replace all instances of a string with another string.

If you have EnableDelayedExpansion on, you can use !var! inside to replace a string with the contents of a variable.

echo Drive of the script file: %~d0
echo Folder of script: %~dp0
echo Full path to script: %~dpnx0
echo First argument: %1
echo Second argument: %2
echo All arguments: %*

Command line arguments: You can use %1, %2, etc to read arguments provided to the script. You can also use %0 and modifiers to get the location of the current script file.

Code flow

rem Call add function, print the result
call :AddFunction 12, 24
echo 12 + 24 = %ReturnValue%

rem Make sure flow never reaches beyond
rem this point.
exit /B 0

rem This function adds the first and
rem second param together, and returns
rem the result in %ReturnValue%.
  set /a ReturnValue=%~1 + %~2
exit /B 0

Local functions: It's possible to create functions inside a single batch script. Call functions with call :LabelName Param1, Param2, ....

Since all variables are shared, the function can set a variable named for example ReturnValue to return a result.

Parameters are available inside the function with %~1, %~2 etc.

Use exit /B [ErrorLevel] to exit a function. You should also usually put all your functions at the end of the script, and make sure flow never reaches them by putting an exit /B 0 at the end of your "main" code.


Pause: This will pause execution and ask the user to "Press any key to continue…"

set /p Answer=Choose 1 or 2: 
if "%Answer%"=="1" goto run
if "%Answer%"=="2" goto exit
echo Please enter the correct choice.
goto choice

Conditional check: You can use an if check to run some code under certain conditions only. See here for more examples, including checking if variables are defined or if files exist.

rem Check if internet is up
ping -n 1 >NUL 2>&1 && echo ONLINE || echo OFFLINE

Chain commands based on exit code: You can use && and || to chain commands together. Commands are executed left-to-right. && executes the right-hand side only if the left hand side returned success (exit code 0), and || is the opposite, it only executes the right hand side if the left hand side failed (non-zero exit code).

adb connect || exit /B 1

Exit on error: You can use the exit command chained with || to stop execution of your script when a command fails.

    set /p Ans=Should I stop? (y/n) 
    if /I "%Ans%"=="y" goto :endloop
    goto :startloop

While loops: You can simulate a while loop using labels and goto. Remember to make sure your label names are unique within the script!

rem Loop through items separated by space
for %%x in (one two three) do ( echo %%x )

rem Loop 1 through 10. Format is (start, step, end)
for /L %%x in (1, 1, 10) do ( echo %%x )

For loops: You can iterate through a sequence of items or a range with for. There are all sorts of ways to use this command, including looping through files, directories, command output, etc.

for /F "delims=" %%a in (file.txt) do (
     echo %%a

Read a file line by line: You can pass delims= to for /F in order to read each line as a whole.

goto :Action2

echo 1

echo 2
goto :eof

echo 3

rem This outputs 2 only

Jump around with labels: You can mark a point in the script with a :label, and then jump to that point with goto :label.

There is also the built-in label :eof which jumps to the end of the script.

ping localhost -n 2 >NUL 2>&1

Fake sleep: Windows doesn't seem to have a built-in sleep function, but you can fake it with ping. You can specify the amount of seconds with -n. Only use 2 or more seconds.

if exist "%~dp0/file.txt" ( echo YES ) else ( echo NO )

Check if file exists: You can also use %~dp0 to get a relative path to the current script, even if the current working directory is somewhere else.

rmdir temp >NUL 2>&1
ping >"%USERPROFILE%\ping.txt" 2>&1

Redirect output text or hide it: You can redirect the output from a command with >. You can specify a file name, or NUL to discard the output. You can also put 2>&1 afterwards if you want to redirect the error output as well.

1 thought on “Batch script cheat sheet

Comments are closed.