In this Daily Drill Down, I’ll show you how to create batch files to help automate tasks. There are many uses for batch files, even in the world of Windows 2000. Any task that can be performed from a command line can be used in a batch file. Even though batch files are not as robust as programming languages, they can be much easier to create and use.
Creating a batch file
Creating a batch file is easy, but you need to make sure that your logic is correct or you’ll end up with some unwanted results. The steps to creating a batch file are design, creation, test, and implementation.
Design
The logic behind a batch file is the most crucial element. You may be able to create complex batch files, but if the logic is not correct, your results can be detrimental. It may help you to lay out the process you want the batch file to follow in a flowchart. It doesn’t have to be a formal chart, just something that allows you to see the process in a conceptual way. Figure A gives a representation of a batch file flowchart.
Figure A |
You should use a flowchart to lay out the logic for complex batch files. |
Creation
Since batch files must be ASCII text with no special characters, a text editor such as Notepad works fine. When Notepad starts, you can type the commands that you would like to have it run. Each new command must be separated by a carriage return. A very simple batch file would look like the following:
REM Delete Temporary Files
C:
Cd\windows\temp
Del *.tmp
The REM command at the beginning of the first line indicates a remark and instructs the batch file to ignore the line. You should use the REM command liberally to document your batch file. The code that you write today may not be easily understood in a few months. The second line instructs the batch file to go to drive C:. The third line uses the CD command to change to the \Windows\Temp folder. The fourth line uses the Del command to delete all files that end with the .tmp extension.
You can use almost any command in a batch file including application file names such as Excel.exe. There are also commands built-in to Windows 95/98/NT/2000 such as the ones used in the example above. Others are:
- Copy—Copies files or folders
- Del—Deletes files or folders
- CD—Changes directory
- MD—Makes a new directory
- RD—Remove or deletes a directory
You can require a user to input command line arguments using the % variables. For instance, if you want to copy the contents of two files into a third file, you could write a batch file to prompt the user for the files.
REM Copyfile.bat
Copy %1 + %2 testfile.txt
After you have finished your batch file, you must save it. You can name the file whatever you wish, but it cannot be the name of internal DOS commands such as Copy, Assign, etc. It must follow the naming restrictions of other files too; such as, it cannot contain the characters / \ : | = ? ” ; [ ] , ^. Batch files must end with the extension .BAT.
Testing and troubleshooting
Some batch files, especially those that delete files, are very powerful and can be very troublesome. It’s a good idea to test your batch file in a nonproduction environment before you implement. For instance, if you want a batch file to automatically delete unwanted log files or temporary files, you can create an identical environment on a test computer.
One-size-fits-all is not a good approach to writing batch files. Let’s say that you create the following batch file to delete log files.
REM This batch file deletes log files
E:
Cd\logfiles
Del *.log
This batch file assumes that the log files will always be located in the logfiles folder on the E: drive. If you try to use this batch file on a different server, you may find that it does not work if the logfiles folder is located on a D: drive.
Batch files run very quickly, which make them difficult to troubleshoot. An effective way to troubleshoot is to break the batch file down into several small logical batch files and run each one individually. You can also use the Pause command in your code to make your batch file wait for you to press a key. For example, let’s say you are deleting files from multiple folders and want to make sure that the logic and syntax is correct. The following batch file has two serious mistakes in it:
REM This batch file deletes files from multiple folders
REM First Series of Commands
C:
Cd\windows\temp
Del *.tmp
Pause
REM Second Series of Commands
D:
Cd download
Del *.exe
Pause
REM Third Series of Commands
E:
Cd logfiles
Del *.*
Pause
The first series of commands completed by the batch file will navigate to the \Windows\Temp folder on the C: drive and delete all .tmp files. It will then pause, waiting for you to press a key. At this point, you can use Windows Explorer or another command prompt to ensure that the proper files have been deleted.
The second series of commands can be troublesome. The command Cd download does not contain the \ character. When you switch to a drive letter in a batch file, it may already be in a subdirectory and therefore requires the \ character for proper redirection. If the Download directory is not found in the current directory, the batch file will flash a quick error message, “Invalid Directory” and then continue to the next line, which is Del *.exe. Using the Pause command will not prevent the files from being deleted, but it will halt the batch file and allow you to terminate it if desired results are not being produced.
The third series of commands makes the same redirection mistake by not using the \ character. By using the Pause command, you can hopefully realize the programming error in the second series of commands and terminate the batch file before the third series is executed. To terminate a batch file that is running, you must press [Ctrl]C.
Implementation
When you are sure that your batch file is working properly and ready to be used in a production environment, copy to the appropriate directory. You can even schedule a batch file to run automatically under Windows NT using the AT or WINAT commands. Windows 2000 has a schedule wizard that steps you through the process.
Examples of batch files
Adding a script file to user accounts
Many commands have undocumented switches and features. The following batch file will use the Net User command to add a script to user accounts. You can add as many users as you want to using this command in a single batch file. This batch file must be run from a domain controller.
REM Addscript.bat
Net user username1 / script:scriptname.bat / domain
Net user username2 / script:scriptname.bat / domain
Net user username3 / script:scriptname.bat / domain
Deleting all files in the current directory
The following batch file deletes all files in the current directory unless they are in use. This can be a dangerous batch file because if you run it in the wrong directory, those files will be difficult or impossible to retrieve. Use this one with extreme caution. There are some safety precautions built in to this batch file. You can expand on the directories in which you do not want it to be used. Click here to view this batch file.
REM Delall.bat
REM If there are no files to be deleted, the batch file goes to the Err label
If not exist *.* Goto err
REM If the batch file is being run from one of the following directories, it REM will go to the label stop and the batch file will terminate. You can add REM your own directories to the list below.
If exist windows\nul goto stop
If exist system\nul goto stop
If exist win95\nul goto stop
If exist win98\nul goto stop
REM The Attrib command below will remove attributes that would prevent REM a file from being deleted
Attrib +a -s -h -r *.*
ECHO Y | DEL.>NUL
GOTO success
:STOP
echo off
cls
ECHO The files you are attempting to delete
ECHO have been protected by the batch file
GOTO end
:Err
echo off
cls
ECHO This directory is empty.
:success
echo off
cls
echo The files in the current directory have been successfully removed.
:END
ECHO.
Multiple parameters
A good use of a batch file is when you have a repetitive task with many parameters. It saves a lot of time by not having to retype the command each time. Click here to see a good example of this.
REM Undel.bat
REM This batch file uses the Undelete command to list recently delete files REM in the current directory
UNDELETE /DOS/LIST | FIND /V /I "NO ENTRIES" | FIND /V /I "OF THOSE," | FIND /V /I "DIRECTO" | FIND /V /I "NOT FOUND" | FIND /V /I "SPECIFICA" | FIND /V /I "ALL RIGHTS" | FIND /V /I "A DELETE PRO" | FIND /V /I "COPYRIGHT" | MORE
ECHO.
Checking a computer’s connectivity on your network
A quick and cheap way to check your servers or important computers for connectivity is by using the Ping utility. You can create a batch file that will ping the computers and send the results to a text file. The following batch file does this and automatically launches the output file in Notepad so you can view the results. Once you have the results file open on your screen, you can search for the words, Request timed out, to determine if a computer is not available. Since this batch file uses the >> to append information to a file, the first command it executes deletes the file if it exists so you will not view old data.
REM Pinglist.bat
Del presults.txt
Ping –a 100.100.100.1 >> presult.txt
Ping –a 100.100.100.2>> presult.txt
Ping –a 100.100.100.3 >> presult.txt
Ping –a 100.100.100.4 >> presult.txt
Ping –a 100.100.100.5 >> presult.txt
Echo. |time >> presult.txt
Notepad presult.txt
Check hard disk space on remote servers
You can use a batch file to monitor the available hard disk space on remote servers and computers. You can use the Dir command and have it look for a file or extension that exists on the hard drive. You may want to do a one-time copy of a file with a unique name to each drive on each server you want to monitor. The reason you don’t want to use *.* is because there will be too much unnecessary information. By searching for a unique filename, all you will get is a single file found along with the available disk space.
REM Freedisk.bat
Del dirsize.txt
Dir \\Servername1\c$\t.zzz >> dirsize.txt
Dir \\Servername1\d$\t.zzz >> dirsize.txt
Dir \\Servername2\c$\t.zzz >> dirsize.txt
Dir \\Servername2\e$\t.zzz >> dirsize.txt
Echo. |time >> dirsize.txt
Notepad dirsize.txt
It’s also possible to put information such as this into a program like Microsoft Excel. You would have to write a macro, however, to organize the data to make the information more readable.
Checking to see when a network segment fails
If you want to monitor a specific computer’s network connection, you can use a batch file in conjunction with the Ping utility.
REM Pingpc.bat
:begin
ping 100.100.100.1 >> pingres.txt
time /T >>pingres.txt
sleep 300
if exist c:\autoexec.bat goto begin
In the batch file, the ping results are sent to a file name Pingres.txt. The next line in the batch file writes the time to the Pingres.txt file so that you will know exactly when the ping was performed. Then, the batch file uses the Sleep.com utility to cause the batch file to wait a specified amount of time in seconds. The next line uses an “if” statement to check for the existence of a known file. This will cause the condition to always be true and the batch file will be in an infinite loop. The logic in this batch file is to continue to ping the computer in question and write the time and output to a file. At any point, you can terminate the batch file and edit the file to search for the point the ping request timed out.
Conclusion
Once you get the hang of writing batch files, it’s not difficult. It’s important to lay out the logic first, and then test your batch files in a nonproduction environment. You can use batch files to make redundant tasks easier. In this Daily Drill Down, I’ve shown you how to create batch files in a Windows NT and Windows 2000 environment. I’ve also given you some handy sample batch files you can use.
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.