Export (0) Print
Expand All
18 out of 23 rated this helpful - Rate this topic

Using Batch Files in Windows NT

Archived content. No warranty is made as to technical accuracy. Content may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.
By Troy Thompson

In this article, I'll discuss the use of batch files and how they can help you get many tasks done quickly. If you thought that batch files were used only in the old MS-DOS® world, you'll have to reconsider them. Batch file programming can be a powerful and timesaving tool. It takes a little programming sense to perform some of the tasks, but it mostly requires being able to lay out a series of tasks in a logical order. You can use batch files to gather data and then to direct the data to a text file. Once your data is in a text file, you can use a database or spreadsheet to arrange and manipulate it. The batch files outlined in this article are examples and guidelines you can use, but you may have to modify them to work in your environment.

Batch File Basics

Your computer can run three types of programs directly, and those files end with the following extensions: .com, .exe, and .bat. A batch file is little more than a series of MS-DOS commands that are separated by carriage returns. Each command in a batch file is run one at a time. You can terminate a batch file by pressing CTRL+BREAK. Almost any executable file can be contained in a batch file, from simple ones, such as Copy and Delete, to application names like Excel. After the batch file has completed its tasks, it returns control to the program that launched it. There is no limit to the length of a batch file, and the computer will continue to carry out the commands until it reaches the end of the file. If a directory has a batch file and an executable file with the same name (Setup.exe versus Setup.bat), the EXE file will be the one that takes precedence.

Batch File Requirements

A batch file must be an ASCII file and cannot contain special characters. Follow these rules:

  • You can give the file whatever name you wish, but it cannot be the name of internal MS-DOS commands, such as Copy, Assign, and so forth. It must follow the naming restrictions of other files, too. For example, it cannot contain the following characters: / \ : | = ? " ; [ ] , ^.

  • The file name must end with the extension .bat.

  • Each line must be separated by a carriage return.


In the MS-DOS environment, this file was important at boot time, along with the Config.sys file. Its use became optional with Microsoft® Windows® 95 and Windows 98. Autoexec.bat could still be used to load MS-DOS drivers for the CD-ROM and sound drivers and to set environment variables. The Autoexec.bat file was probably the first batch file to which most people were introduced. It was also one of the first major files that users would examine when troubleshooting a software problem in a PC.

Real-Life Batch Files

In this section, I'll discuss the use of real-life batch files.

Gathering Data

You can use a batch file to gather and redirect information to a file. In the following example, the batch file Drvdata.bat uses the DIRUSE command to gather directory information from drive X:

diruse /s x:\ > drvdata.txt
\progra~1\micros~1\office\excel.exe x:\drvdata.txt

The DIRUSE command is found on the Windows NT Option Pack CD. This command does not show individual file usage, just directory usage. The /s parameter tells it to gather information from all subdirectories, too. Then, with the redirect symbol (>), the output from the file is redirected to a file called Drvdata.txt. The purpose of this batch file is to gather the total file size of each directory and subdirectory for manipulation in a spreadsheet or database. Windows will show you the size of the first level of directories on a drive, but it can't give you the overall picture of directories and their subdirectories at once.

For instance, you may have a drive with 400 directories on it. You could use Windows Explorer to show you the directories and even to sort them, but you have no way of knowing how much data is contained in the subdirectories of any one directory. You can right-click the directory name and choose Properties to see a single directory at a time, but that does not give you the overall picture.

After the information is gathered, the program switches back to drive C and launches a Microsoft Excel spreadsheet with the command-line argument of the filename to import the file automatically. At this point, you can create a macro to sort, delete, or format the data.

You may think that this seems like a convoluted process, but sometimes it's the only way to get the information you need quickly. The Drvdata batch file contains only five lines and doesn't take long to create. You just have to understand the logic of the batch-file-writing process before you start.

Microsoft Exchange Batch File

The Csvall.bat file uses the Microsoft Exchange Administrator program (Admin.exe) to pull header and data information from a Microsoft Exchange Server. This information is extremely valuable if your data becomes corrupted and you have to rebuild your mailboxes. The Jet database format used with Exchange Server version 5.x can become corrupted. Sometimes you can repair the process with the Exchange utilities; sometimes you can't. It's even worse if you've been backing up a corrupted database without realizing it. At that point, it's difficult to restore from a backup.

The following batch file uses the Admin program with the /E option, which exports data. Then, it uses the /O option to point to an Options file that contains information about the server from which you are going to retrieve information.


If you have multiple Exchange servers, you can use this one batch file to retrieve information from all of them. Simply copy the existing lines and change them to point to the correct files. Once you get the batch file set up the way you want it, you can create an icon for it and place it on your desktop. Then, all you have to do is double-click the icon and let the batch file do the work in the background. The few minutes it takes to create the batch file and the few seconds it takes to run will save you countless hours of rebuilding mailboxes.

Microsoft Systems Management Server

In the next batch file, I'll supply SMS distribution points with a new virus update. If one server is set to download the update, you can use a batch file to copy it to multiple locations. This batch file starts by using the NET USE command to map drives to the servers.

net use k: \\server1\virus
net use w: \\smsdist1\virus
net use x: \\smsdist2\virus
net use y: \\smsdist3\virus
net use z: \\smsdist4\virus
copy k:\???????.exe w:\vupdate.exe
copy k:\???????.exe x:\vupdate.exe
copy k:\???????.exe y:\vupdate.exe
copy k:\???????.exe z:\vupdate.exe
net use k: /DELETE
net use w: /DELETE
net use x: /DELETE
net use y: /DELETE
net use z: /DELETE

With NET USE, five drives are mapped: k, w, x, y, and z. Drive k contains the file to be copied. Since many virus update files change names to reflect the date, this batch file copies the executable in the directory that has seven letters plus the extension .exe to each of the drives that were mapped. This approach, using the question mark [?] to represent characters, will work only in specific situations. You must think it through before using it, or you may get unexpected results. However, it demonstrates the unusual things you can do in a batch file. Once the file is copied to the respective drives, the NET USE command removes the drive mapping with the /DELETE switch.

Stopping Services

The following batch file shows how you can stop and start services. It comes in handy when you need to stop a service in order to back up data. Many databases stay open continuously and cannot be backed up while open. You can buy third-party software that enables you to back up almost any application that's open, but that approach can be expensive. Let's say you have an SQL database that needs to be backed up once a day. You can create a batch file to stop the services automatically and run the backup agent:

Net Stop "SQL Database Service"
ntbackup operation path [/a][/v][/r][/d "text"][/b
][/hc:{on | off}] [/t {option}][/l "filename"][/e][/tape
Net Start "SQL Database Service"

This three-line batch file will stop the SQL service, back up the data, and restart the service when the backup is complete. For this example, the syntax is shown for the Windows NTBackup utility. The main problem arises when users need the database open all day and the only good time to back up is at midnight. That can also be remedied easily. If you use the AT command to schedule your backup every night at 11:59 PM, it's no longer necessary for you to be there. All you have to do is check the log file each morning to make sure that your backup was successful.

The Scheduler Service must be running before you can use the AT command. You can start the Scheduler Service from the Services Applet in Control Panel or from a command prompt by typing C:\> net start schedule.

To use the AT command to schedule the batch file named Backup.bat, type the following line at the command prompt:

AT 23:59 /EVERY:M,T,W,Th,F backup.bat

This command will schedule the Backup.bat file to run at 11:59 PM on Monday, Tuesday, Wednesday, Thursday, and Friday. It may be necessary to use the drive letter and the path of the location of the batch file if you do not have a path already set to its location. Also, if you need to use a space in the command portion, you would have to use quotation marks around the command, as in:

AT 23:59 /EVERY:M,T,W,Th,F "vupdate.exe /q"

The /q is a command-line argument that you will want to pass to the program, and it requires a space between the .exe and the switch.

Other Uses for Batch Files

Now I'll discuss other uses for batch files.

Computer Cleanup

Many organizations hire temporary employees who are issued computers. After the employees leave, it may be necessary to clean up files from the computers. Some manufacturers, such as Dell Computer Corporation, have devised a restore command that will reset the computers to the state they were in when shipped from the factory. It can be a handy tool, but it removes any application software and network settings that you have configured. You can use a batch file to delete, move, or copy information from the computer quickly and easily. For this example, I'll delete all files in the C:\tempemp directory and then move all spreadsheets from the C:\Excel directory to a server:

del /Q *.*
move *.* \\server1\sheets

Replaceable Parameters

The purpose of a replaceable parameter is to enable you to specify a different variable each time the batch file is run. Otherwise, you would have to edit the batch file each time you wanted to vary information.

MS-DOS parses each command line by breaking it into pieces that are delimited by spaces. Each piece is placed in a temporary holding area called %0, %1, %2, %3, %4, %5, %6, %7, %8, or %9. The first piece is the command itself, and it's represented by %0. The remaining pieces are considered variables. The second piece is considered the first parameter, represented by %1, and so on.

The following batch file enables you to take two files and swap their names. This batch file uses variables to represent the filenames. You can use this batch file to swap the names of only those files that reside in the same directory and drive.

IF "%1"=="" GOTO NAME
IF "%2"=="" GOTO NAME
ECHO %1 is now named %2
ECHO and %2 is now named %1.
ECHO One or both of the filenames you typed,
ECHO (%1 and %2), are absent from the
ECHO current directory:
ECHO You must specify two (2) files
ECHO whose names you want to swap.
ECHO Example - SWAP file1.doc file2.doc

Storing variables with the [%], you can use the batch file over and over without having to edit it each time.

Be Careful

Great care should be taken when writing a batch file that deletes or moves files or directories. Test your batch file in a non-production environment first. If you're like most programmers, you will use code that you find on the Internet, in other programs, and from similar sources. Depending on the batch file, it may not produce the same results on one system as it does on another.

Compiling Batch Files

There are a couple of drawbacks with using batch files. They are slow to execute because they are run line by line, with MS-DOS closing and reopening the file after each individual line is read. They are also easy to modify, which can create problems. BAT2EXEC (Douglas Boling, PC Magazine, August 1990) is a compiler for batch files, and it turns your batch file into a COM file. Compiled batch files execute faster and create a source code that is protected from change. Before you compile a batch file, be sure to save the original under another name. Once you have compiled the file using BAT2EXEC, you cannot uncompile it to make changes.


Batch files are not a thing of the past. Some administrators who didn't grow up in the MS-DOS era may not recognize the potential of batch files as valuable tools. You can use batch files to do certain things that would take a considerable amount of time and effort otherwise. They are best used for tasks that are redundant in nature. If you haven't tried using batch files, I highly recommend that you give them a try.

Troy Thompson, MCSE+Internet, has worked in the automation field for 15 years, dealing with a variety of systems, including Wang OIS, Unisys BTOS, UNIX, Windows 3.11, Novell NetWare, Windows NT 3.51, and Windows NT 4.0. He also worked as an administrator of a Novell and Windows NT network and as a systems analyst for an IBM mainframe. Currently, Troy is the Information System Security Officer at the Information Management shop at Fort Knox. If you'd like to contact Troy, send him an e-mail troy@bridepub.com .

The above article is courtesy of TechRepublic http://www.techrepublic.com .

We at Microsoft Corporation hope that the information in this work is valuable to you. Your use of the information contained in this work, however, is at your sole risk. All information in this work is provided "as -is", without any warranty, whether express or implied, of its accuracy, completeness, fitness for a particular purpose, title or non-infringement, and none of the third-party products or information mentioned in the work are authored, recommended, supported or guaranteed by Microsoft Corporation. Microsoft Corporation shall not be liable for any damages you may sustain by using this information, whether direct, indirect, special, incidental or consequential, even if it has been advised of the possibility of such damages. All prices for products mentioned in this document are subject to change without notice.

International rights.

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
© 2014 Microsoft. All rights reserved.