Batch File Cheat Sheet



  • Batch Script Tutorial
  1. Batch File Cheat Sheet Printable
  2. Batch Script Cheat Sheet
  3. Batch File Cheat Sheet Examples
  • Batch Script Resources

Batch Files File Input @echo off echo Bill file echo Gate file set /P fileco ntent =file echo First Line:%filec ontent% set /P var=file FOR /f%%f in (file) Do (echo%%f) REM print each line in file Variables setlocal set MYENV=abc endlocal Only active in the current batch file (local) set MYENV=abc creates or changes an enviro. Batch-Cheat-Sheet.md Batch Cheat Sheet. For more information on a specific command, type HELP command-name. Suspends processing of a batch file and displays a message. $ p batch-setup These are the default configuration options for when running the Phoronix Test Suite in a batch mode (i.e. Running phoronix-test-suite batch-benchmark universe). Running in a batch mode is designed to be as autonomous as possible, except for where you'd like any end-user interaction. As discussed in the previous tutorial, a batch file is an unformatted text file or script file which contains multiple batch file commands or instructions to achieve a certain task. It has extension of.bat or.cmd. Click here to go through the introduction of the batch file before learning batch file commands. Batch file commands: Windows/DOS.

  • Selected Reading

Command Prompt Cheat Sheet.CMD Cheat Sheet. First thing to remember its a way of operating a computer. It's the way we did it before WIMP (Windows, Icons, Mouse, Popup menus) became common.Getting Help. For general help. Type `Help` in the command prompt.


In this chapter, we will look at some of the frequently used batch commands.

S.NoCommands & Description
1VER

This batch command shows the version of MS-DOS you are using.

2ASSOC

This is a batch command that associates an extension with a file type (FTYPE), displays existing associations, or deletes an association.

3CD

This batch command helps in making changes to a different directory, or displays the current directory.

4CLS

This batch command clears the screen.

5COPY

This batch command is used for copying files from one location to the other.

6DEL

This batch command deletes files and not directories.

7DIR

This batch command lists the contents of a directory.

8DATE

This batch command help to find the system date.

9ECHO

This batch command displays messages, or turns command echoing on or off.

10EXIT

This batch command exits the DOS console.

11MD

This batch command creates a new directory in the current location.

12MOVE

This batch command moves files or directories between directories.

13PATH

This batch command displays or sets the path variable.

14PAUSE

This batch command prompts the user and waits for a line of input to be entered.

15PROMPT

This batch command can be used to change or reset the cmd.exe prompt.

16RD

This batch command removes directories, but the directories need to be empty before they can be removed.

17REN

Renames files and directories

18REM

This batch command is used for remarks in batch files, preventing the content of the remark from being executed.

19START

This batch command starts a program in new window, or opens a document.

20TIME

This batch command sets or displays the time.

21TYPE

This batch command prints the content of a file or files to the output.

22VOL

This batch command displays the volume labels.

23ATTRIB

Displays or sets the attributes of the files in the curret directory

24CHKDSK

This batch command checks the disk for any problems.

25CHOICE

This batch command provides a list of options to the user.

26CMD

This batch command invokes another instance of command prompt.

27COMP

This batch command compares 2 files based on the file size.

28CONVERT

This batch command converts a volume from FAT16 or FAT32 file system to NTFS file system.

29DRIVERQUERY

This batch command shows all installed device drivers and their properties.

30EXPAND

This batch command extracts files from compressed .cab cabinet files.

31FIND

This batch command searches for a string in files or input, outputting matching lines.

32FORMAT

This batch command formats a disk to use Windows-supported file system such as FAT, FAT32 or NTFS, thereby overwriting the previous content of the disk.

33HELP

This batch command shows the list of Windows-supplied commands.

34IPCONFIG

This batch command displays Windows IP Configuration. Shows configuration by connection and the name of that connection.

35LABEL

This batch command adds, sets or removes a disk label.

36MORE

This batch command displays the contents of a file or files, one screen at a time.

37NET

Provides various network services, depending on the command used.

38PING

This batch command sends ICMP/IP 'echo' packets over the network to the designated address.

39SHUTDOWN

This batch command shuts down a computer, or logs off the current user.

40SORT

This batch command takes the input from a source file and sorts its contents alphabetically, from A to Z or Z to A. It prints the output on the console.

41SUBST

This batch command assigns a drive letter to a local folder, displays current assignments, or removes an assignment.

42SYSTEMINFO

This batch command shows configuration of a computer and its operating system.

43TASKKILL

This batch command ends one or more tasks.

44TASKLIST

This batch command lists tasks, including task name and process id (PID).

45XCOPY

This batch command copies files and directories in a more advanced way.

46TREE

This batch command displays a tree of all subdirectories of the current directory to any level of recursion or depth.

47FC

This batch command lists the actual differences between two files.

48DISKPART

This batch command shows and configures the properties of disk partitions.

49TITLE

This batch command sets the title displayed in the console window.

50SET

Displays the list of environment variables on the current system.

Help

help comman­dNamecomman­dName /?help --> show all system commands

All System Commands

help

Clear Screen

Clear Screencls

Shortcuts

TabAutoco­mpletearrow keys up/downback/f­orward history commandsControl + Cstops current commandALT + F7clears the historyF7shows the history

Directory Make & Remove

mkdir
subdir­ectorycreates new subdir­ectorymkdir subdir­/su­bsubdircreates subdir & subdir­/su­bsubdir
Hint: creates it, if they aren't existingrmdirremoves an empty dirrmdir /s directoryremoves directory with contentrmdir /s /q directoryremoves directory with content & skips y/n question

Directory copy

copy src dstcopy filescopy /Y src destcopy files overwrites with­out quesitonxcopy /s src destcopies dirs and subdirs except empty onesxcopy /YS src destas above with­out ask to overwritexcopy /YS src serv­er­shareFilecopy to network sharerobocopy /S src destcopies dirs and subdirs except empty onesrobocopy /YS src destas above without ask to overwrite

Parameters

%0Name of Script%1 ... %9Parameter 1 ... Parameter 9%*prints all parameters as a string(one line)
for %%x in (%*) do echo %%xaccess it through a for loop works with > 10 parameters

Pass Parameters to sub script

parame­ter­s_s­cri­pt.bat@echo off
call parame­ter­s_s­ubs­cri­pt.bat %*
EXIT /B %error­level%parame­ter­s_s­ubs­cri­pt.bat@ECHO off
echo subscript called with %*
EXIT /B 0EXIT /B specifies to exit the current batch scropt instead of cmd.exe. If executed from outside a batch script, it will quit cmd.exe

Arrays Way2

set array[0]=0
set array[1]=1
...set value to a specific array elementecho %array[0]%
echo %array[1]%access to array elementsmissing loop over elements: indexed

Functions: label and goto

echo 'Hi:'
goto :good:bad
echo 'I don't like scripting'
goto :eof:good
echo 'I like scripting'
goto :eof

Double­Cli­ckE­xec­ution

@ECHO off
setlocal
REM check for intera­ctive sesseion
SET intera­ctive=0
ECHO %CMDCM­DLINE% | FINDSTR /L %COMSPEC% >NUL 2>&1
IF %ERROR­LEVEL% EQ SET intera­ctive=1
ECHO do work
REM pause if intera­ctive (doubl­e-c­licked execution)
IF '­%in­era­cti­ve%­' '­0' PAUSE
EXIT /B 0FINDSTR /L is use search string literally

Navigation

realativeparent directorycd .., cd..subdir­ectorycd subdir­ectoyabsolutecd C:Windowscd Windowschange driveZ:

Wildcards

? (file?.txt)one arbitary character* ( *.bat)arbitary characters (0,1 or more)

File Show

type fileshow file contentmoreshow file content page­wisesort fileshow file content sorted

Directory show Content

current folderdirabsolute pathdir C:Windowsdir Y:different drivedir /Bonly show file names and directory names

Batch Files User Input

@ echo off
set /P name='Input yor name: 'Syntax: set /P var=pr­ompt:echo Hi %name%variable call

Batch Files File Input

@echo off
echo Bill > file
echo Gate >> fileset /P fileco­ntent =< file
echo First Line: %filec­ontent%set /P var=< fileFOR /f %%f in (file) Do (
echo %%f
)REM print each line in file

Variables

setlocal
set MY_ENV=abc
endlocalOnly active in the current batch file (local)set MY_ENV=abccreates or changes an enviro­nment variable that is active in the cmd. (global)setshows the active enviro­nment variablesecho %USERNAME%print variable outdefined MY_VARreturns
0 => Execution was successful
>0 => Execution failed

IF Control Structures

IF test (command) ELSE (command)Syntax

Control structures For

for {%%|%}­<Va­ria­ble> in (<S­et>) do <Co­mma­nd> [<C­omm­and­Lin­eOp­tio­ns>]cmd.exe use ->%batch script use ->­%%

Functions

call :print­_name Florianecho print_name exitst with %error­level%goto :eof:printname
echo Hit %1
exit /B 0 <- REM sets exit status of :print­_name

File Rename & Move

rename file1 file2renamef filte1 to file2move file1 dirmove file 1 to dir (path dir/file1)move file1 dir/file2moves and renames file1 to file2 (path: dir/file2) file2 is overwr­itten from file1move /Y file1 file2moves and overwrites file1 to file2 with­out asking

File Names

Case-I­nse­nsitiveMax. 260 characters incl. invisible termin­ating null characterspaces and character set 128 - 255 allowedNever <, >, :, ', /, , |, ?, *Hint: A-Z, a-z, 0-9, _, spaces, ( underscore as space )*.bat & *.cmddir /B --> only show file names and directory Names

Directory Rename & Move

rename dir1 dir2renames dir1 in dir2move dir1 dir2if dir2 exist: dir1 into dir2 (path: dir2/d­ir1), else rename dir1 to dir2move file1 dir/file2file 2 is deleted. file1 get the name of file2 ans is set at the position of file2 with asking (Yes/N­o/All)move /Y file1 file2file 2 is deleted. file1 get the name of file2 ans is set at the position of file2 with­out asking.

File Redirects

type file.txt | sortgive output of type to sortsort < file.txtgive content ( stdin) of file.txtecho '­hi' > file.txtwrite '­hi' (stout) to file.txttype NUL > file.txtcreate empty filerm file 2> errors.txtredi­rects errors­(st­derr) ro errors.txtrm file 2> NULdiscard errorsrm file 2>&1redi­rect stderr to stdoutecho '­you­' >> file.txtappend '­you­' to file.txt

Comment

REMPräfix after them the text

Calcul­ation

set /a i=0
echo i=%i%set /a i=1+1 Operatoren +, -, *, /set /a i+=1 Operatoren +, -, *, /

Arrays Way1

set arra­y=1 2 3 4
%array%(echo) all Array elementsfor %%a in (%array%) do (
echo%%a
)loop over elementsset array=­(and nothing else)unset vari­able or array

Control Struct­ures: Comparison Operators

OperatorInfoEqualEQUEqualNEQ!=Not equalLSS<LessLEQ<=Less than or equal toGTR>Greater thanGEQ>=Greater than or equalNOT!Not

Editors

NotepadNotepad++Visual­Stu­dioCode

Editors

NotepadNotepad++Visual­Stu­dioCodeAtom

Terminals

cmd.exeWindows TerminalConEmucmder

Batch Filex Exit / Return

Specify exit code:echo 'abc'
exit 0Query error levelecho %ERROR­LEVEL%Exit/R­eturn codes0 => Execution was successful

Batch File Cheat Sheet Printable


Batch Script Cheat Sheet

>0 => Execution fiales with code X

Batch File Cheat Sheet Examples