- Batch Script Tutorial
- 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.No | Commands & Description |
---|---|
1 | VER This batch command shows the version of MS-DOS you are using. |
2 | ASSOC This is a batch command that associates an extension with a file type (FTYPE), displays existing associations, or deletes an association. |
3 | CD This batch command helps in making changes to a different directory, or displays the current directory. |
4 | CLS This batch command clears the screen. |
5 | COPY This batch command is used for copying files from one location to the other. |
6 | DEL This batch command deletes files and not directories. |
7 | DIR This batch command lists the contents of a directory. |
8 | DATE This batch command help to find the system date. |
9 | ECHO This batch command displays messages, or turns command echoing on or off. |
10 | EXIT This batch command exits the DOS console. |
11 | MD This batch command creates a new directory in the current location. |
12 | MOVE This batch command moves files or directories between directories. |
13 | PATH This batch command displays or sets the path variable. |
14 | PAUSE This batch command prompts the user and waits for a line of input to be entered. |
15 | PROMPT This batch command can be used to change or reset the cmd.exe prompt. |
16 | RD This batch command removes directories, but the directories need to be empty before they can be removed. |
17 | REN Renames files and directories |
18 | REM This batch command is used for remarks in batch files, preventing the content of the remark from being executed. |
19 | START This batch command starts a program in new window, or opens a document. |
20 | TIME This batch command sets or displays the time. |
21 | TYPE This batch command prints the content of a file or files to the output. |
22 | VOL This batch command displays the volume labels. |
23 | ATTRIB Displays or sets the attributes of the files in the curret directory |
24 | CHKDSK This batch command checks the disk for any problems. |
25 | CHOICE This batch command provides a list of options to the user. |
26 | CMD This batch command invokes another instance of command prompt. |
27 | COMP This batch command compares 2 files based on the file size. |
28 | CONVERT This batch command converts a volume from FAT16 or FAT32 file system to NTFS file system. |
29 | DRIVERQUERY This batch command shows all installed device drivers and their properties. |
30 | EXPAND This batch command extracts files from compressed .cab cabinet files. |
31 | FIND This batch command searches for a string in files or input, outputting matching lines. |
32 | FORMAT 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. |
33 | HELP This batch command shows the list of Windows-supplied commands. |
34 | IPCONFIG This batch command displays Windows IP Configuration. Shows configuration by connection and the name of that connection. |
35 | LABEL This batch command adds, sets or removes a disk label. |
36 | MORE This batch command displays the contents of a file or files, one screen at a time. |
37 | NET Provides various network services, depending on the command used. |
38 | PING This batch command sends ICMP/IP 'echo' packets over the network to the designated address. |
39 | SHUTDOWN This batch command shuts down a computer, or logs off the current user. |
40 | SORT 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. |
41 | SUBST This batch command assigns a drive letter to a local folder, displays current assignments, or removes an assignment. |
42 | SYSTEMINFO This batch command shows configuration of a computer and its operating system. |
43 | TASKKILL This batch command ends one or more tasks. |
44 | TASKLIST This batch command lists tasks, including task name and process id (PID). |
45 | XCOPY This batch command copies files and directories in a more advanced way. |
46 | TREE This batch command displays a tree of all subdirectories of the current directory to any level of recursion or depth. |
47 | FC This batch command lists the actual differences between two files. |
48 | DISKPART This batch command shows and configures the properties of disk partitions. |
49 | TITLE This batch command sets the title displayed in the console window. |
50 | SET Displays the list of environment variables on the current system. |
Help
help commandNamecommandName /?help --> show all system commandsAll System Commands
helpClear Screen
Clear ScreenclsShortcuts
TabAutocompletearrow keys up/downback/forward history commandsControl + Cstops current commandALT + F7clears the historyF7shows the historyDirectory Make & Remove
mkdirsubdirectorycreates new subdirectorymkdir subdir/subsubdircreates subdir & subdir/subsubdir
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 without quesitonxcopy /s src destcopies dirs and subdirs except empty onesxcopy /YS src destas above without ask to overwritexcopy /YS src serversharecopy to network sharerobocopy /S src destcopies dirs and subdirs except empty onesrobocopy /YS src destas above without ask to overwriteParameters
%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
parameters_script.bat@echo offcall parameters_subscript.bat %*
EXIT /B %errorlevel%parameters_subscript.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]=0set 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
DoubleClickExecution
@ECHO offsetlocal
REM check for interactive sesseion
SET interactive=0
ECHO %CMDCMDLINE% | FINDSTR /L %COMSPEC% >NUL 2>&1
IF %ERRORLEVEL% EQ SET interactive=1
ECHO do work
REM pause if interactive (double-clicked execution)
IF '%ineractive%' '0' PAUSE
EXIT /B 0FINDSTR /L is use search string literally
Navigation
realativeparent directorycd .., cd..subdirectorycd subdirectoyabsolutecd 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 pagewisesort fileshow file content sortedDirectory show Content
current folderdirabsolute pathdir C:Windowsdir Y:different drivedir /Bonly show file names and directory namesBatch Files User Input
@ echo offset /P name='Input yor name: 'Syntax: set /P var=prompt:echo Hi %name%variable call
Batch Files File Input
@echo offecho Bill > file
echo Gate >> fileset /P filecontent =< file
echo First Line: %filecontent%set /P var=< fileFOR /f %%f in (file) Do (
echo %%f
)REM print each line in file
Variables
setlocalset MY_ENV=abc
endlocalOnly active in the current batch file (local)set MY_ENV=abccreates or changes an environment variable that is active in the cmd. (global)setshows the active environment variablesecho %USERNAME%print variable outdefined MY_VARreturns
0 => Execution was successful
>0 => Execution failed
IF Control Structures
IF test (command) ELSE (command)SyntaxControl structures For
for {%%|%}<Variable> in (<Set>) do <Command> [<CommandLineOptions>]cmd.exe use ->%batch script use ->%%Functions
call :print_name Florianecho print_name exitst with %errorlevel%goto :eof:printnameecho 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 overwritten from file1move /Y file1 file2moves and overwrites file1 to file2 without askingFile Names
Case-InsensitiveMax. 260 characters incl. invisible terminating 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 NamesDirectory Rename & Move
rename dir1 dir2renames dir1 in dir2move dir1 dir2if dir2 exist: dir1 into dir2 (path: dir2/dir1), 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/No/All)move /Y file1 file2file 2 is deleted. file1 get the name of file2 ans is set at the position of file2 without 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 filerm file 2> errors.txtredirects errors(stderr) ro errors.txtrm file 2> NULdiscard errorsrm file 2>&1redirect stderr to stdoutecho 'you' >> file.txtappend 'you' to file.txtComment
REMPräfix after them the textCalculation
set /a i=0echo i=%i%set /a i=1+1 Operatoren +, -, *, /set /a i+=1 Operatoren +, -, *, /
Arrays Way1
set array=1 2 3 4%array%(echo) all Array elementsfor %%a in (%array%) do (
echo%%a
)loop over elementsset array=(and nothing else)unset variable or array
Control Structures: Comparison Operators
OperatorInfoEqualEQUEqualNEQ!=Not equalLSS<LessLEQ<=Less than or equal toGTR>Greater thanGEQ>=Greater than or equalNOT!NotEditors
NotepadNotepad++VisualStudioCodeEditors
NotepadNotepad++VisualStudioCodeAtomTerminals
cmd.exeWindows TerminalConEmucmderBatch Filex Exit / Return
Specify exit code:echo 'abc'exit 0Query error levelecho %ERRORLEVEL%Exit/Return codes0 => Execution was successful