Enterprise Software

Configure IT Quick: Using batch files in Windows NT

Examples and guidelines you can use for manipulating batch files in Windows NT

In this Daily Drill Down, we’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 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 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.

Autoexec.bat
In the DOS environment, this file was important at boot time, along with the Config.sys file. Its use became optional with Windows 95/98. Autoexec.bat could still be used to load 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, we’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:
DRVDATA.BAT
X:
cd\
diruse /s x:\ > drvdata.txt
c:
\progra~1\micros~1\office\excel.exe x:\drvdata.txt


The DIRUSE command is found on the 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 Microsoft 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.
CSVall.bat
ADMIN /E d:\CSV\site\HEADER2.CSV /O d:\CSV\site\OPTION.TXT
ADMIN /E d:\CSV\site\DATA.CSV /O d:\CSV\site\OPTION.TXT

Option.txt
[Export]
DirectoryService=Server1
HomeServer=Server1
ExportObject=Mailbox
InformationLevel=Minimal
BasepointOnly=No
RawMode=No
Hiddenobjects=Yes
Subcontainers=Yes
CodePage=0


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, we’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.
Copyvirus.bat
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 allows 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
:{n}]
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 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 typingC:\> 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 we’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, we’ll delete all files in the C:\tempemp directory and then move all spreadsheets from the C:\Excel directory to a server:
Tempemp.bat
C:
cd\tempemp
del /Q *.*
cd\Excel
move *.* \\server1\sheets


Replaceable parameters
The purpose of a replaceable parameter is to allow 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.

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 allows 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.
Swap.bat
IF "%1"=="" GOTO NAME
IF "%2"=="" GOTO NAME
IF NOT EXIST %1 GOTO ERROR
IF NOT EXIST %2 GOTO ERROR

:PROCESS
RENAME %1 TTT1
RENAME %2 TTT2
RENAME TTT2 %1
RENAME TTT1 %2
ECHO.
ECHO %1 is now named %2
ECHO and %2 is now named %1.
GOTO END

:ERROR
ECHO.
ECHO One or both of the filenames you typed,
ECHO (%1 and %2), are absent from the
ECHO current directory:
ECHO.
CD
GOTO END

:NAME
ECHO.
ECHO You must specify two (2) files
ECHO whose names you want to swap.
ECHO Example - SWAP file1.doc file2.doc
:END
ECHO.


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 file 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 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.

Conclusion
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 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 .

The authors and editors have taken care in preparation of the content contained herein, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for any damages. Always have a verified backup before making any changes.
0 comments