Writing DOS Bat Files

This lecture is being written for Windows 2000 and XP although most of the concepts and commands hold true for other versions of Windows and DOS. DOS Bat files are command scripts for DOS. I.e., they are files that contain DOS commands. Bat files are executed by the command processor. Simply type the name of the Bat file at the command prompt and press Enter.

  • Basic Commands
    Any DOS command may be placed in a Bat file. So, for example, the commands DIR and PATH may be placed in a Bat file and will produce the same output they do when executed interactively.
    You can open a DOS window to execute these commands by clicking on SART- RUN and then typing cmd or command. cmd causes cmd.exe to execute and command causes command.com to execute. See below for the technical difference in cmd and command.
    The Difference in .COM and .EXE programs
    Programs with .com and .exe extensions both contain executable machine code. .com programs are compact executables that have limitations such as a limited address space that make them smaller and sometimes faster. .exe files may be full 32-bit applications.

  • The Difference between cmd and command
    cmd.exe is the Windows NT/2000/XP command line interface. It is a 32 bit command prompt that supports long filenames natively and other advanced features such as autocompletion of filenames in XP (use the TAB button to autocomplete). Command.com is a 16 bit DOS shell which is used for older DOS compatibility. It runs inside the NTVDM (NT Virtual DOS Machine). In NT/W2000/Xp command.com actually uses cmd.exe to execute commands on its behalf. Because command.com is backward compatible with old versions of DOS it does not support a number of advanced commands that execute in cmd.exe. Command.com runs Bat files as separate processes whereas Bat files run at the shell level when using cmd.
    Neither of these create a native DOS environment in NT/W200X/Xp. Due to the nature of these more modern operating systems NTVDM must interpret all commands. Thus, the default and best choice now is to use CMD rather than COMMAND as the shell.

    You may see a list of DOS commands by typing
    Help at the command prompt.
    You can see help on a particular command by typing
    Help [command name]

  • DOS Variables
    Just like in "real" programming languages Bat files may use variables. They are two types of variables that may be used in Bat files. They are environment variables and replaceable parameters.

    Environment variables may be defined within or outside of Bat files. When using command.com Bat files run as processes so environment variables defined inside of Bat files only exist while that process exists. Many environment variables are used both outside of and within Bat files. You may inspect these at the command line. When using cmd.exe the scope of environment variables defined in Bat files are global unless they are enclosed within setlocal/endlocal commands.
    The Set command is used to create environment variables. The general syntax for set is
    SET EnvironmentVariable=string
    Be careful not use spaces around the = sign.
    For example,
    SET ClientName=John Doe
    sets an environment variable named ClientName to the string "John Doe"
    Executing the SET command with no parameters displays all environment variables.
    For more information on the SET command type HELP SET or review this description of SET.

    User Input Since the inception of DOS one of the greatest obstacles to writing useful .bat files has been the inability to get user input. With Command Extensions introduced in Windows 2000 and present in XP and 2003 one may now use the SET command to input text from the user as follows.
    SET /P variable=[promptString]
    The above command displays the specified promptString before reading a line of input from the user. promptString may be null.
    Variable substring extraction - Command Extensions now support variable substring extraction.
    Find out more about The SET command and Command Extensions

    Replaceable Parameters are parameters specified on the command line when invoking a Bat file. Inside the Bat file the first parameter may be referenced as %1, the second as %2 and so on.

  • Echo command - The echo command is used to display data. It may display string constants or variables. It may be used both interactively and in Bat files. In order to display the contents of a variable the variable must be enclosed in % signs.
    Examples,
    echo path
    This simply display the word "path"
    echo %path%
    This displays the contents of the path environment variable.

    Example Bat file, SeeParams
    SeeParams hello world will invoke the Bat file, SeeParams, and pass it two params, the first being "hello" and the second being "world".

    SeeParams
    echo This is the SeeParams Bat file
    echo %1
    echo %2


    More on the echo command. When Bat files execute, by default, they display each line of the Bat file before the line executes.
    We modify this behavior with the echo command.
    echo off turns off command line echoing and
    echo on turns it back on again.
    Finally, echo. (note the dot following echo) writes a blank line.

  • Calling Bat Files as Subprograms. Good programming practice says that we should modularize our code. The primary way of doing this is to use subprograms. We may write Bat files that may be called from other Bat files. However if we simply invoke the subBat file with its name alone then when the subBat file ends so will the calling Bat file. I.e., it will not return to the calling Bat file. In order to use subBat files properly we should use the CALL DOS command. For example if our subBat file is named sub then we would invoke it with call sub. Of course you may pass parameters to the subBat file just as you would to a bat file invoked on the command line.

    One may also call a "local" subprogram. A local subprogram is a block of code located in the same bat file as the main program. The block of code begins with a label which is the object of the CALL and ends with exit /B

  • Pipes, Filters and Redirection of I/O
    A good description of pipes, filters and redirection of I/O comes to us from Caldera.
    Redirection of I/O
    Ordinarily output from a command or program goes to the monitor/display. Oftentimes we would like the output to be sent elsewhere such as a file. The right angle bracket enables us to do this.
    For example,
    DIR > folder.lis
    Creates a file called folder.lis and sends the output of the DIR command to that file. If the file folder.lis already exists it is superceded.

    Using two right angle brackets appends the output to the indicated file so that
    DIR > > folder.lis
    Appends the output of the DIR command to folder.lis. If folder.lis does not exist then it is automatically created.

    Input to a command or a program is normally expected to come from the keyboard. The left angle bracket can be used so that a program or command may accept input from a file or another device. The most common use of redirection of input is to have a filter accept input from a file.

    Filters are programs or commands that read input, process it in some way, and output the result.
    For example the sort command reads input lines, sorts them and outputs the result. The sort command is normally used with redirection of I/O.
    For example suppose the file Names.lis contains a list of names, one per line.
    sort Names.lis >>SortedNames.lis
    Reads the names in the file Names.lis rearranges them into alphabetical order and writes the result to the file SortedNames.lis.

    Pipes are a mechanism for routing input and output from one program or command to another. The vertical bar symbol | is used to designate a pipe connection between two programs.

  • Find is used to search for a text string in a file or files.

    FindStr is a much more powerful version of Find that can use regular expressions.

    A Pipe example
    dir | find ".htm"
    The above command runs dir to generate a list of all files in the current directory. It then pipes the output to find which displays all of the output lines from dir containing the string .htm.
    The objective is to list all .htm files in the current directory.

  • Conditional Execution in Bat Files - The IF command

    ErrorLevel is an integer value that may be returned/set by a program to indicate that the program did or did not complete execution normally. ErrorLevel = 0 indicates that the program did complete execution normally. Errorlevels greater than 0 indicate an abnormal termination or error. The precise meaning of any number greater than 0 is program dependent. Errorlevel may be checked in a Bat file with special syntax defined and illustrated in the links below.

    The Exists keyword acts like a function that determines if a specified file exists.

    Syntax and options for the IF command.
    Examples of using the IF command.

  • Programming Loops in Bat Files
    The FOR - IN - DO command performs loop processing in Bat files.
    Syntax, options and examples for the FOR command.
    More examples of using the FOR command.

  • Managing Users
    The CACLS command displays or modifies access control lists (ACLs) of files. These are used to control what users have access to files and what level access they have.

  • Process and Job Creation and Management
    The Start command enables one to start a new process running a particular image or Bat file in a window.
    Help Start shows options re: priority, window style, etc..

    RUNAS enables one to run a program as another user. This is normally used to run a program as Administrator without logging out and logging back in as Asministrator.
    typing runas /? at the cmd prompt will give complete details on how to use this command.

    Tasklist displays a list of all running processes on the system.
    tasklist /? will display help on this command.

    Taskkill enables the user to kill (stop/terminate) a process.
    taskkill /? will display help on this command.

    Using the Windows taskmanager will give you a good idea of what tasklist and taskkill can do. Taskmanager can be invoked by typing Ctrl-Alt_Del and selecting taskmanager. If you prefer you can run taskmanager from C:\Windows\System32\taskmgr.exe.

    SC (Service Controller) enables the user to manage system services and device drivers.
    sc /? will display help on this command.

  • The AT command schedules commands and programs to run on a computer at a specified time and date. The Schedule service must be running to use the AT command. Syntax and options for the AT command.
    Examples of using the AT command.
    You may also schedule tasks using the Windows GUI task scheduler. Goto Control Panel, Scheduled Tasks, Add Scheduled Tasks and follow the wizard.

    The Windows Task Scheduler may also be used to schedule jobs to run at a later time.

  • Backing Up Your System
    The Replace Command copies files from one location to another. It contains options designed to facilitate performing backups.
    Example
    replace c:\Docs\*.* d:\Docs /s /u
    replaces (updates) all files in d:\Docs and all its subdirectories with files of the same name in c:\Docs and all its subdirectories if the dates of the source files are more recent than the dates of the destination files.

    The ntbackup command utility is both a command line utility and a windows utility with a wizard designed to help you backup your system.

    Perhaps the method of backup that works most reliably over all Windows system is the use of XCOPY.
    To backup your PC use the XCopy command as follows

    xcopy source-folder destination-folder /y/d/s
    rem /y automatically confirms that you want to overwrite the file
    rem /d only copies new files or files with newer dates
    rem /s copy subdirectories and their files as well

    Placing multiple XCOPY commands in a .bat file customized for your computer will enable you to backup only those directories containing user files and/or those subject to change.

  • Network Management
    A description of networking commands

    Learning the internals of protocols - Information on RFCs




  • Top of this page   Top of page      Home page   Home page