Batch file (Microsoft)

From Library
Jump to navigation Jump to search
Batch file
A script for use on the command-line of MS-DOS (also valid in config.sys files) or in the Microsoft Windows command processor ('cmd.exe').

Quick Reference

Basic commands:

  • CALL, ECHO, FOR, GOTO, IF, PAUSE, REM, and SHIFT

Command list:

  • @, %DIGIT, %VARIABLE%, CALL, CLS, ECHO, FOR, GOTO, IF, PAUSE, REM, SET, SHIFT


Comments

  • use :: or REM:
    • REM: statements are echoed to the console unless preceded with a @ (on the same line) or Echo off.
    • They can thus be used for 'debug'/'verbose' mode feedback and a limited form of self-documenting code.
    • : actually defines a label, and must occur as the first non-whitespace character in a line. This method generally cannot be used for comments within code blocks, if statements, for loops, etc., as they are interpreted as a single command line by `cmd.exe`. It may work for comments inside those blocks as long as it is 'sandwiched' between two actual commands.
    • See the text and links at: https://www.robvanderwoude.com/comments.php
  • %= inline comments =% may work under certain circumstances
  • use @ to prevent display of any single command (valid in MS-DOS 3.3 and later); e.g. @REM This is a hidden remark

Variables

set [variable=[value]]
Assigns a value to a variable; e.g. set var1=1 sets var1 to the number 1
Clears an existing environment variable
%var1%
Uses the value of a variable (either a temporary / local variable or a system-wide 'environment' variable')
There may be no 'local' variables???
!var1!
Uses the value of a variable when delayed variable expansion is enabled

Conditional statements

IF
if [not] condition command
if [not] string1==string2 command
if [not] exist filename command

Loops and execution control

for %%argument in (list) do command
Runs contents once time for each member of a list
Example: for /F "delims=" %%a in ('findstr /I "start, ani" %tmp%\*.txt')
goto LABEL
Execution moves to :LABEL
call [drive:][path]filename [batch-parameters]
'Includes' another batch file by reference, and executes it before continuing


User input and feedback

echo
1. print a string to the terminal
2. turns on/off command echoing, or displays current echo status
3. automatically answers prompts from other commands, e.g. echo Y|Del *.*
%DIGIT
Uses command-line parameters as read-only(?) variables
%0 is the entire command statement
%1 is the first parameter, %2 is the second, ...
SHIFT
Shifts each parameter left one position (i.e. 'pops' one parameter off of a stack; the previous parameter %1 will no longer exist)
CLS
Clears the screen, similar to the POSIX command clear
TYPE
Displays the contents of a file??
PAUSE
Pauses, with or without a prompt, until a key (or <Ctrl-Break>) is pressed.

Output redirection

command > nul
Same as POSIX > /dev/null
command > file
Redirects output to file
command >> file
Appends output to file
command < file
Contents of file used as inputs to command??

Other

DOS environment variables

%PATH%
the current search path
%PROMPT%
the current command prompt string

Windows environment variables

%USERNAME%
the current command prompt string
%windir%
the current command prompt string

DOS commands of note

HELP
COPY
MOVE
FORMAT
REPLACE
XCOPY

CHOICE
This tool allows users to select one item from a list of choices and returns the index of the selected choice.

Windows commands of note

Windows cmd.exe help

from Windows 10 (version 10.0.19044 / Build 19044)
help

For more information on a specific command, type HELP command-name
ASSOC          Displays or modifies file extension associations.
ATTRIB         Displays or changes file attributes.
BREAK          Sets or clears extended CTRL+C checking.
BCDEDIT        Sets properties in boot database to control boot loading.
CACLS          Displays or modifies access control lists (ACLs) of files.
CALL           Calls one batch program from another.
CD             Displays the name of or changes the current directory.
CHCP           Displays or sets the active code page number.
CHDIR          Displays the name of or changes the current directory.
CHKDSK         Checks a disk and displays a status report.
CHKNTFS        Displays or modifies the checking of disk at boot time.
CLS            Clears the screen.
CMD            Starts a new instance of the Windows command interpreter.
COLOR          Sets the default console foreground and background colors.
COMP           Compares the contents of two files or sets of files.
COMPACT        Displays or alters the compression of files on NTFS partitions.
CONVERT        Converts FAT volumes to NTFS.  You cannot convert the
               current drive.
COPY           Copies one or more files to another location.
DATE           Displays or sets the date.
DEL            Deletes one or more files.
DIR            Displays a list of files and subdirectories in a directory.
DISKPART       Displays or configures Disk Partition properties.
DOSKEY         Edits command lines, recalls Windows commands, and
               creates macros.
DRIVERQUERY    Displays current device driver status and properties.
ECHO           Displays messages, or turns command echoing on or off.
ENDLOCAL       Ends localization of environment changes in a batch file.
ERASE          Deletes one or more files.
EXIT           Quits the CMD.EXE program (command interpreter).
FC             Compares two files or sets of files, and displays the
               differences between them.
FIND           Searches for a text string in a file or files.
FINDSTR        Searches for strings in files.
FOR            Runs a specified command for each file in a set of files.
FORMAT         Formats a disk for use with Windows.
FSUTIL         Displays or configures the file system properties.
FTYPE          Displays or modifies file types used in file extension
               associations.
GOTO           Directs the Windows command interpreter to a labeled line in
               a batch program.
GPRESULT       Displays Group Policy information for machine or user.
GRAFTABL       Enables Windows to display an extended character set in
               graphics mode.
HELP           Provides Help information for Windows commands.
ICACLS         Display, modify, backup, or restore ACLs for files and
               directories.
IF             Performs conditional processing in batch programs.
LABEL          Creates, changes, or deletes the volume label of a disk.
MD             Creates a directory.
MKDIR          Creates a directory.
MKLINK         Creates Symbolic Links and Hard Links
MODE           Configures a system device.
MORE           Displays output one screen at a time.
MOVE           Moves one or more files from one directory to another
               directory.
OPENFILES      Displays files opened by remote users for a file share.
PATH           Displays or sets a search path for executable files.
PAUSE          Suspends processing of a batch file and displays a message.
POPD           Restores the previous value of the current directory saved by
               PUSHD.
PRINT          Prints a text file.
PROMPT         Changes the Windows command prompt.
PUSHD          Saves the current directory then changes it.
RD             Removes a directory.
RECOVER        Recovers readable information from a bad or defective disk.
REM            Records comments (remarks) in batch files or CONFIG.SYS.
REN            Renames a file or files.
RENAME         Renames a file or files.
REPLACE        Replaces files.
RMDIR          Removes a directory.
ROBOCOPY       Advanced utility to copy files and directory trees
SET            Displays, sets, or removes Windows environment variables.
SETLOCAL       Begins localization of environment changes in a batch file.
SC             Displays or configures services (background processes).
SCHTASKS       Schedules commands and programs to run on a computer.
SHIFT          Shifts the position of replaceable parameters in batch files.
SHUTDOWN       Allows proper local or remote shutdown of machine.
SORT           Sorts input.
START          Starts a separate window to run a specified program or command.
SUBST          Associates a path with a drive letter.
SYSTEMINFO     Displays machine specific properties and configuration.
TASKLIST       Displays all currently running tasks including services.
TASKKILL       Kill or stop a running process or application.
TIME           Displays or sets the system time.
TITLE          Sets the window title for a CMD.EXE session.
TREE           Graphically displays the directory structure of a drive or
               path.
TYPE           Displays the contents of a text file.
VER            Displays the Windows version.
VERIFY         Tells Windows whether to verify that your files are written
               correctly to a disk.
VOL            Displays a disk volume label and serial number.
XCOPY          Copies files and directory trees.
WMIC           Displays WMI information inside interactive command shell.

For more information on tools see the command-line reference in the online help.

Lessons learned

  • Use the help (command name) command to see usage information for most valid built-in commands.
    • Many commands may also respond to (commandname) /?
  • Find current environment variables using `SystemPropertiesAdvanced.exe` or `set`

Further reading

See also: wikipedia:Batch file

References