Batch files have been around since the early Ms DOS days. They are text files that contain a list of command-line executables. They can be compared to UNIX shell scripting, but are much simpler. For a file to be recognized by (Microsoft's DOS shell) it needs to have a .bat extension.

  • To print a message on the screen use the echo command. For example:
    echo Hello, World!

  • By default the commands in a batch file are displayed at the prompt before being executed. To prevent this from happening start every command with an At sign '@' or enter the following command at the top of the file:
    @echo off

  • To use arguments passed to the batch file use the Percent sign '%' followed by the argument's number, for example to use the second and fourth arguments with echo:
    echo Second Arg: %2, Fourth Arg: %4

  • To redirect the output to a new file use the Greater Than sign '>'. If the file exists it will be overwritten. Here is an example that will save the directory listing to a file called dirlist.txt:
    dir > dirlist.txt

  • To append the redirected output to the end of an existing file use 2 Greater Than signs next to each other '>>'. The following example appends another directory listing to the file from the previous example:
    dir >> dirlist.txt

  • To display the contents of a text file use the type command. Here is an example that displays the contents of the dirlist.txt file:
    type C:\dirlist.txt

  • Conditional processing is done using the if else statement. Following is an example that checks if a file exists before displaying its contents:
    if exist C:\dirlist.txt (
        type C:\dirlist.txt
    ) else (
        echo The file does not exist.