ADVANCED BATCH FILES
Read This First!
(Skip to the Batch Files)
Here are more examples of advanced batch files. As with the first Advanced Batch File Examples, the title remarks should suffice so you'll understand their operation, although some may be preceded by a syntax example. In addition, some lines have notes to the side. These explanatory notes are not part of the file. Do not type them in. For the most complicated examples, explanations follow the file itself.
Before delving into this page, be sure to have read Batch File Basics regarding the techniques for writing batch files. Note that because this is an advanced page and that you should have read the previous batch file articles at this site, that not every little thing will be explained.
Once again, the "DR" command is a batch file that runs the Color Directory program I use. You may substitute the DOS "DIR" command with its switches set to your preferences, or any DOS directory display program. Also, it is assumed that you are placing all batch files into the "C:\BATCH" directory and that it is in your Path.
Finally, be aware that Doctor DOS will not be responsible for any problems resulting from the use or mis-use of anything presented here.
An advisory to non-Canadians: Some characters shown in some batch
files here may not be able to be reproduced on your system unless
the Country Code is changed or you type them in as ASCII characters.
Consult your text editor/word processor manual to see how to do the latter.
EXCEPT FOR THE BATCH FILES THEMSELVES,
INFORMATION ON THESE BATCH FILE PAGES
MAY NOT BE REPRODUCED WITHOUT PERMISSION
FROM THE AUTHOR ©
THE BATCH FILES ARE FOR PERSONAL USE ONLY.
THEY MAY NOT BE SOLD OR OTHERWISE DISTRIBUTED.
AN AUTOMATIC BACKUP ROUTINE
This is a simple backup batch file that will archive files residing in a given directory into a single .zip file and place that .zip file into a BACKUP directory. As a bonus, the .zip file will automatically be given a name made from the current date. Improvements are given afterwards that will allow the file to be run automatically on a weekday of choice upon boot up, and also to delete old archive files back before a specified previous time.
Date operations will be handled by an update to the DOS "SET" command called "XSET". It reduces the code required to get the date into an environment variable to just one line, so no extra files are required, as was the case with CTULD.bat in the first Advanced Batch Files. An explanation follows each part and an XSET link will be given at the end.
Those of you with the %DATE% variable built into your version of DOS may eliminate the XSET lines that are used to get the date into the environment and rework the remainder of file to take this into account.
It will be assumed that you are backing up all files from a directory named "DATA" to a directory named "BACKUP", that you are using PKZIP, which is located in a "PKZIP" directory under a "UTIL" directory, and that you have placed XSET into the DOS directory -- all of which are located on the `C' drive. It is also assumed that you boot the computer each morning.
You must first create the C:\BACKUP directory yourself. Once it's created, it will be available for this purpose and it will eventually contain a series of.zip archive files in chronological order. From any of these you may recreate your data files as they were at the start of any given date. You may change any or all of these directories to suit your setup or purpose. If you prefer to use another compression program, change the "PKZIP" reference & directory to match the program you plan to use.
:: BU.bat :: Archives All Files from the C:\DATA directory into a .ZIP file :: The .zip File is Placed into the C:\BACKUP directory. :: @ECHO OFF C:\DOS\XSET CUR-DATE DATE YY-MM-DD C:\UTIL\PKZIP\PKZIP C:\BACKUP\%CUR-DATE%.ZIP C:\DATA\*.* :END SET CUR-DATE= ________
This file starts by using XSET to place the current date into the environment as a variable called "CUR-DATE". It is in the form of a two-digit year, two-digit month, and two-digit day (YY-MM-DD). Next, PKZIP is used to compress copies of all the files in the DATA directory into one zip file called (date).zip. So if you are working on files and it is January 22nd, 2007, the backup file will be called "07-01-22.zip". Finally, the "CUR-DATE" variable is reset to remove it from memory. That's it! Simple, huh?
Now, it would be handy if this operation could be done automatically on say, every Monday morning upon bootup. This would give a backup of the previous week's files every Monday. Here's that version:
:: BU.bat (Improved) :: Archives All Files from the C:\DATA directory into a .ZIP file :: The .zip File is Placed into the C:\BACKUP directory. :: This is Done Every Monday Morning Upon Bootup :: @ECHO OFF C:\DOS\XSET DAY DAYOFWEEK IF NOT "%DAY%" == "1" GOTO END :BACKUP C:\DOS\XSET CUR-DATE DATE YY-MM-DD C:\UTIL\PKZIP\PKZIP C:\BACKUP\%CUR-DATE%.ZIP C:\DATA\*.* :END SET CUR-DATE= SET DAY= ________
In this version, XSET is used to place the day of the week into the environment variable "DAY". XSET uses the numbers "0 - 7" to represent the days of the week "Sunday - Saturday". Thus, Monday is Day Number 1. Our batch file above tests to see if it's Monday, by seeing if the variable equals `1'. If it does not, the batch file ends. If it does, the test line is ignored and the file moves on to BACKUP where the backup is performed as in the first version of the batch file. In either case, any variables made are set to equal nothing to remove them from memory. This is done via DOS' "SET" command, which is capable of doing the job, and also be faster at it than XSET because it's an internal DOS command.
For this file to work automatically, place a command near the end of your AUTOEXEC.bat to run the "BU.bat" file. Upon bootup on Monday mornings, the previous week's DATA files will be backed up into a compressed archive. If you go this route, be sure to use the "CALL" command so that DOS will return to the AUTOEXEC.bat afterwards so as to finish it. The syntax is: CALL C:\BATCH\BU.BAT.
This is all fine & dandy until you have to reboot during the day on which the backup has been performed. With the above example, the backup routine would run again but would include any changed files from the current week's Monday. That would spoil the "snapshot" of the previous week's files as seen at the end of that week. The solution is to have the batch file ask if the previous week's backup file already exists before doing the backup routine:
:: BU.bat (Improvement 2) :: Archives All Files from the C:\DATA directory into a .ZIP file :: The .zip File is Placed into the C:\BACKUP directory. :: This is Done Every Monday Morning Upon First Bootup Only :: @ECHO OFF C:\DOS\XSET DAY DAYOFWEEK IF NOT "%DAY%" == "1" GOTO END :BACKUP C:\DOS\XSET CUR-DATE DATE YY-MM-DD IF EXIST C:\BACKUP\%CUR-DATE%.ZIP GOTO FILE C:\UTIL\PKZIP\PKZIP C:\BACKUP\%CUR-DATE%.ZIP C:\DATA\*.* GOTO END :FILE ECHO. ECHO %CUR-DATE%.ZIP File Already Exists! ECHO No Additional Backup Performed. ECHO. :END SET CUR-DATE= SET DAY= ________
It would now be nice if old backups could be deleted automatically so they don't accumulate and use space on your hard drive unnecessarily. Let's say that any backup older than about three months is not necessary to keep. This would mean that there would be approximately a dozen backups in the archive at any one time from after about the first three months that this setup is first implemented.
:: BU.bat (Improvement 3) :: Archives All Files from the C:\DATA directory into a .ZIP file :: The .zip File is Placed into the C:\BACKUP directory. :: This is Done Every Monday Morning Upon Bootup :: Deletes Backup Files Older than 90 Days. :: @ECHO OFF C:\DOS\XSET DAY DAYOFWEEK IF NOT "%DAY%" == "1" GOTO END :BACKUP C:\DOS\XSET CUR-DATE DATE YY-MM-DD IF EXIST C:\BACKUP\%CUR-DATE%.ZIP GOTO FILE C:\UTIL\PKZIP\PKZIP C:\BACKUP\%CUR-DATE%.ZIP C:\DATA\*.* XXCOPY C:\BACKUP\*.ZIP /DB#90 /RSY /PD0 /ED GOTO END :FILE ECHO. ECHO %CUR-DATE%.ZIP File Already Exists! ECHO No Additional Backup Performed. ECHO. :END SET DAY= SET CUR-DATE= ________
This file is the same as the previous except for the "XXCOPY" command. This is an update of the DOS "XCOPY" command. With the switches shown, it selects files with a date on, or before, 90 days from the present (/DB#90), allows for those files to be removed from the source directory (C:\BACKUP) with the prompt answered "YES" (/RSY), hides any additional prompt display (/PD0), and preserves the directory should it be, or become, empty (/ED). (Switches make for powerful program and DOS usage. See here for a DOS Switches Discussion.)
XSET may be obtained from
XXCOPY may be obtained from -XXCOPY.com.
The CLEARING HOUSE
This batch file is one of several similar ones I use to do routine file work. I employ my DOWNLOAD, UPLOAD or TEMP directory for this purpose. Batch files have been written that will allow the moving or copying of all, or specified, files in a directory to, or from, any of those three directories. Thus those directories become clearing houses for these files because they are just passing through from a source directory to a target directory. Some GUI users employ the desktop for similar purposes.
This is handy when you want to move files from one directory to another and don't want the tedium of file managers like Windoze Extorturer, (Windows Explorer), nor wish to have to type all the Path and directory names for the source and target. Six files are required should you wish to use all three directories, as do I. I will show only one of them, but you may modify this file to complete the sextet.
I use three directories because I sometimes have other files sitting in one or more due to on-going work, so having three means more of a chance one or more will be empty. In actuality, this is not even a problem, because i have written very specific versions of these batch files for my own use. These leave alone the files already in the directory I choose to use as the Clearing House while the other work goes on around them.
I won't get into these right now. Perhaps I'll add one of them at a later date so you may see how those work. I also use hard drive directories rather than RAM drive ones so that I can leave these files there and come back to them several days later, if needed. If they were on a RAM drive, I might forget about them, reboot, and lose them.
Here is one of my basic "Clearing House" batch files:
:: CTTP.bat :: Copies All or Specified Files to the C:\TEMP Directory :: Wildcard Selections are Allowed :: Prompts to Overwrite when Necessary :: @ECHO OFF IF "%1" == "" GOTO COPY-ALL If there is no file specified, IF NOT "%1" == "" GOTO COPY-SPEC All files will be copied. Otherwise, the Specified Files will be copied. :COPY-ALL ECHO. Inserts a Blank Line on Screen XCOPY *.* C:\TEMP /-Y Copies All Files, with Prompting GOTO END for Overwrite :COPY-SPEC XCOPY %1 C:\TEMP:\ /-Y > NUL See Text, Below SHIFT IF "%1" == "" GOTO END GOTO COPY-SPEC END: ECHO. DR C:\TEMP Display the TEMP Directory ________
For the "COPY-ALL" section, the chosen file(s) are copied to the C:\TEMP directory with all prompts in place so you may monitor the operation. Blank lines are inserted on screen to keep this information separated.
In the "COPY-SPEC" section, the first file given on the command line will be copied. The SHIFT command then moves the file names you gave down by one position. That is, file 2 becomes `1', `3' becomes `2', and so on. If there is no file left to move into Position `1', the batch file is directed to the end. Otherwise, it is told to go back to COPY-SPEC where the next file is copied. Then SHIFT is executed again. As long as files are being moved into Position `1', the batch file will continue to copy. When none are left, the file will be directed to the end where a directory listing confirms the operation.
Now write a second file by copying this. Rearrange the copy commands to copy *from* the TEMP directory to the current one. Use `.' to represent the current directory. Call the new file "CFTP" for "Copy From Temp".
In use, go to the source directory and issue the CTTP command. Then go to the target directory and issue CFTP. All the files will have been transferred. To make this less painless, make shortcuts to the source & target directories. If you are sure you don't need the TEMP directory copies, delete them. If you don't need *any* copies except for those in the final target directory, substitute "MOVE" for "XCOPY" in the previous two batch files. You will also have to move "/-Y" so as to place this just after each "MOVE" command. For some reason Microsoft changed the syntax to not allow switches for the "MOVE" command to be at the end of the line. Instead, they must directly follow the command. Don't forget to have a space between the command and any switches. (DR-DOS (dee-are dos) users need to eliminate any `/-Y' because DR-DOS does not use this switch.)
Now rewrite all those files but substitute "Download" and "Upload" for "Temp". You now have three clearing house directories. If you do both to and from, use both copy and move, and use all three directories, a total of twelve batch files will result.
I have this set up in combination with many direct-access batch files for my most used directories. Thus, with one command I access the directory of choice, then issue another command to move or copy the files to one of the "clearing house" directories. A third command takes me to the target directory and the final command moves or copies the files from the clearing directory to the target directory. To speed "Move" operations, use a RAM drive TEMP directory. Since they are being moved, you don't need to worry about saving any additional copies, so RAM drive reboot losses are not a factor unless power was to be lost during the operation.
To speed operations further, I have a many of these batch files keyed to shortcut keys, so it's often only a matter of pressing four keys/key combinations to get some mighty fast and painless files chores done. It can often be finished before something like Windoze Extorturer can even be opened!
UPDATE: Since I first wrote the clearing house batch files, I composed a batch file that allows direct copy or move operations and skips the "middle man" step. It requires a change-directory program or batch-file shortcuts to the target directory in order to work. I use -Directory Maven for most of this purpose. TRAN.bat (Transfer bat) is too advanced for this section but may seen on the Advanced Batch Files III page.
USING DATES IN FILE and DIRECTORY NAMES
:: DATEFILE.bat :: Makes a Text File with the Current Date as the Name :: C:\BATCH\DOS\XSET CUR-DATE DATE YY-MM-DD See Text for REM >: %CUR-DATE%.TXT XSET Information
This will make a zero-byte file which name will be in the format of "Year-Month-Day". That keeps similar files in chronological order. You may then load it into an editor and add text. Here's a version that does both:
:: DATEFILE.bat (Improved) :: Makes a Text File with the Current Date as the Name :: Loads it into DOS EDIT :: C:\BATCH\DOS\XSET CUR-DATE DATE YY-MM-DD C:\BATCH\DOS\EDIT %CUR-DATE%.TXT
This assumes you are using DOS EDIT and it is in the "DOS" directory. XSET is an update to the DOS "SET" command. It is assumed here that it too, is in the "DOS" directory. Get that program at the XSET website.
Those of you with the %DATE% variable built into your version of DOS may eliminate the XSET lines that are used to get the date into the environment and rework the remainder of file to take this into account.
Here's a way to rename an existing file with the current date.
:: DATEFILE.bat (Alternate) :: Renames a Text File with the Current Date as the Name :: The File Extension is Kept :: :: Syntax: DATEFILE (file name and extension) :: C:\BATCH\DOS\XSET CUR-DATE DATE YY-MM-DD REN %1.* %CUR-DATE%.*
Want to make a directory with the current date as its name?
:: DATE-DIR.bat :: Makes a Directory with the Current Date as the Name :: C:\BATCH\DOS\XSET CUR-DATE DATE YY-MM-DD MD %CUR-DATE% ________
This renames a directory with the current date as its name
:: DATE-DIR.bat (Alternate) :: Makes a Directory with the Current Date as the Name :: May not be Used with Directories having an Extension in the Name :: :: Syntax: DATE-DIR (file name and extension) :: :: C:\BATCH\DOS\XSET CUR-DATE DATE YY-MM-DD MOVE %1 %CUR-DATE%
A SPACE-SAVER SYSTEM
Here's the scenario: Your hard drive is running low on room and you can't afford, or don't want to bother getting, a new one. You'd like to keep some files in a compressed archive but hate the idea of having to uncompress a given file to edit it, and then having to restore an updated version back into the compressed archive.
This batch file will allow you to retrieve a document from a .zip file, edit it, and then return the modified version to the .zip file. The example will be geared for plain text files, but you may substitute a word processor so that this batch file could retrieve, say a WordPerfect file, load it into that program, and then return it to the .zip file upon exit. You may also use the second version of this batch file as a simple viewer for files in that .zip archive.
For this example, it will be assumed that your compression program is PKZIP and it is in a subdirectory of C:\UTIL, and that you are using DOS EDIT. Any text editor will work provided you can specify a file to load right from the command line. Be aware, any file you load with this setup must be in the .zip file & directory shown, although you could modify this example to take into account different .zip files residing in different directories. Alternatively, you could write a series of these batch files, each for a specific .zip file.
It will be also be assumed that your documents are archived in DOCS.zip and that is in the C:\DOCUMENT directory.
:: EDZIP.bat :: Allows a File to be Retrieved from a .zip Archive for Editing. :: @ECHO OFF IF "%1" == "" GOTO NOFILE IF NOT EXIST C:\DOCUMENT\ED-TEMP\NUL MD C:\DOCUMENT\ED-TEMP C: CD\DOCUMENTS\ED-TEMP C:\UTIL\PKZIP\PKUNZIP C:\DOCUMENT\DOCS.ZIP %1 C:\DOS\EDIT %1 C:\UTIL\PKZIP\PKZIP -m- C:\DOCUMENT\DOCS.ZIP %1 GOTO END :NOFILE ECHO. ECHO No File Given for Editing ECHO. :END ________
First, the batch file checks to make sure you typed a file name at the command line. Then it checks to see if there is an ED-TEMP directory and creates one if there is not. Next, it moves you to this directory for the editing job. This directory is necessary because if the same file name as you are about to expand existed in the DOCUMENT directory, PKUNZIP would want to overwrite it. It does ask before doing so, but this is an unnecessary step. Editing within an empty directory prevents this step.
Next, the file is expanded (retrieved from the archive) and loaded into EDIT. After exiting EDIT, control returns to this batch file and the file is reinserted into DOCS.zip where it overwrites the previous version. Note the " -m- " switch. This moves the expanded file into the zip archive, effectively removing it from the directory. This is to prevent expanded files from cluttering the directory and taking up space should you forget to delete it after editing. Here, this deletion is taken care of for you. Be sure that switch is in lower case. The trailing minus sign is there to prevent PKZIP from deleting the directory should it be empty after the file is moved. (In actuality, the directory should be empty because it is only supposed to be used as a temporary editing location.)
To speed this process, set PKZIP's workspace to be on a RAM drive by adding a "SET" line before any PK work in the batch file. This might be something like "SET PKTMP=F:\TEMP". (Substitute your RAM drive's letter for the `F' shown here.) As well, if you place EDIT on the RAM drive and point the batch file's EDIT lines there, you'll have the fastest speed of operations possible.
Now what happens if you mistype the file name or you don't remember the name? Here's an improved version that will take that into consideration:
:: EDZIP.bat (Improved) :: Allows a File to be Retrieved from a .zip Archive for Editing. :: Allows Viewing of the .zip Archive :: @ECHO OFF IF "%1" == "" GOTO VIEW :EDITING IF NOT EXIST C:\DOCUMENT\ED-TEMP\NUL MD C:\DOCUMENT\ED-TEMP C: CD\DOCUMENTS\ED-TEMP C:\UTIL\PKZIP\PKUNZIP C:\DOCUMENT\DOCS.ZIP %1 IF ERRORLEVEL 11 IF NOT ERRORLEVEL 12 GOTO NOFILE C:\DOS\EDIT %1 C:\UTIL\PKZIP\PKZIP -m- C:\DOCUMENT\DOCS.ZIP %1 :VIEW C:\UTIL\PKZIP\PKZIP -vbnm C:\DOCUMENT\DOCS.ZIP GOTO END :NOFILE ECHO. ECHO File "%1" was not Found in DOCS.zip ECHO Batch File Terminated ECHO. :END ________
In this version, if no file name is typed at the command line, DOCS.zip's contents are viewed as a brief listing, sorted by name, and displayed a page at a time via the " -vbnm " switch. (The `m' stands for "more".) If you wish to edit one of the files, you may then run the batch file again and add one of the file names at the command line. If the name you type does not exist, PKUNZIP's errorlevels are used to determine this. Then a message is displayed and the batch file ends. After a successful edit, the contents of DOCS.zip are displayed a page at a time for conformation.
It would be handy that if when you type a name that does not exist, you had the option to create that file and add it to the .zip archive. This means that you would not have to add it manually and also means that this one batch file can now serve a triple purpose. These purposes are to be able to view the DOCS.zip contents, edit an existing file in that archive, and to be able to place new files into the archive. Here's that version:
:: EDZIP.bat (Improvement 2) Requires DOS 6 or Newer. :: Allows a File to be Retrieved from a .zip Archive for Editing. :: Allows Creation of a New File and Addition of it to the Archive. :: Allows Viewing of the .zip Archive :: @ECHO OFF IF "%1" == "" GOTO VIEW :EDITING IF NOT EXIST C:\DOCUMENT\ED-TEMP\NUL MD C:\DOCUMENT\ED-TEMP C: CD\DOCUMENTS\ED-TEMP C:\UTIL\PKZIP\PKUNZIP C:\DOCUMENT\DOCS.ZIP %1 IF ERRORLEVEL 11 IF NOT ERRORLEVEL 12 GOTO NOFILE C:\DOS\EDIT %1 C:\UTIL\PKZIP\PKZIP -m- C:\DOCUMENT\DOCS.ZIP %1 :VIEW C:\UTIL\PKZIP\PKUNZIP -vbnm C:\DOCUMENT\DOCS.ZIP GOTO END :NOFILE ECHO. ECHO File "%1" was not Found in DOCS.zip ECHO. ECHO Do you Wish to Create this File? ECHO If so, Press `C' ECHO If Not, Press "ESCAPE" to End CHOICE /C:C<- /N > NUL IF ERRORLEVEL 2 GOTO END IF ERRORLEVEL 1 GOTO CREATE GOTO END :CREATE C:\DOS\EDIT %1 C:\UTIL\PKZIP\PKZIP -m- C:\DOCUMENT\DOCS.ZIP %1 C:\UTIL\PKZIP\PKUNZIP -vbnm C:\DOCUMENT\DOCS.ZIP :END ________
|(Note that `<- ' represents the "Escape" character. To create it, press ^P (Control-P) in DOS Edit, then the "Escape" key. Other text editors allow one to create the "Escape" character by pressing ^V first.)|
In this final version, PKUNZIP tries to extract from DOCS.zip the file you gave at the command line. If it finds it, the file is extracted, edited, and reinserted into the archive as before. If the file name is not found, the option is given via the DOS "CHOICE" command to create this new file. If that option is selected, the file is created and then added to DOCS.zip. As a bonus, if the DOCS.zip file does not exist, it too will be created. Thus, you may start using this batch file as soon as you create the C:\DOCUMENT directory because it will do the rest. As before, the contents of DOCS.zip is shown a page at a time for conformation.
DELETED FILE SECURITY
This batch file allows a deleted file's contents to be made unrecoverable by DOS UNDELETE and by many commercial undelete programs. It is not perfect because there are other ways to recover the file. However, the casual snoop will not be able to view or recover the deleted file's contents.
:: EXPUNGE.bat :: Expunges Files :: UNDELETE Cannot Recover Them :: Wildcards may be Used :: @ECHO OFF IF "%1" == "*TASKS*" GOTO TASKS ECHO. ECHO These files will be Expunged: ECHO. ECHO %1 %2 %3 %4 %5 %6 %7 %8 %9 ECHO. ECHO Continue? Y? N? ECHO. CHOICE > NUL IF ERRORLEVEL 2 GOTO END IF ERRORLEVEL 1 GOTO DEL-ALL GOTO END :DEL-ALL FOR %%F IN (%1) DO CALL C:\BATCH\EXPUNGE.BAT *TASKS* %%F SHIFT IF "%1" == "" GOTO END GOTO DEL-ALL :TASKS REM >: %2 DEL %2 > NUL ECHO. ECHO %2 Expunged! ECHO. :END
Ignore the opening "IF" statement for a moment. Next are displayed up to nine of the files you have selected for expunging. You may type more names, but only the first nine appear on the screen. It then asks if you want to continue. This is done via the DOS "CHOICE" command. Pressing `n', ends the batch file. Pressing `y' continues on to the "DEL-ALL" section. The CHOICE command's output is directed to NUL to prevent its prompts from showing on the screen.
In "DEL-ALL", the DOS "FOR-IN-DO" (FOR) command is used. It essentially says: "FOR each Item listed INside the Brackets, DO call the EXPUNGE batch file". However, it is given a first parameter of "*TASKS*", while the second parameter will now be the first file to be expunged. "%%F" represents that first file name you typed because it will in turn represent each file name designated by "%1".
This time, when EXPUNGE.bat is run, the first "IF" statement is true and control passes to the "TASKS" section. There, the DOS "REM" (Remark) command is used to create a new file with no information in it, but using the same name as the one you typed at the command line. This overwrites your file's name with this new one, which incidently contains no information. That is, it is zero bytes in size. Then, this new file is deleted.
Having completed the procedure, control returns to the "FOR" statement. Since there was only one parameter (%1) in there, "FOR" is finished and the SHIFT line is executed. SHIFT is used to move the file names you typed at the command line to one lower position with regards to the percent-number replaceable parameters. Thus, the second file name you typed is moved to position number one (%1). Since %1 is equal to something, this makes the next "IF" statement false, so the batch file does not go to the end. Instead, the succeeding line is read and that sends the batch file back to the "DEL-ALL" section where it reads the "FOR" line once again.
Here, because of SHIFT, there is a new number one (%1) file. It is actually the second file name you typed, but SHIFT has moved it into position number one (%1). So the process is repeated with this second file name (now in position one) passed to the TASKS section where it is expunged. This procedure continues until all files have been removed.
Simply type "EXPUNGE filename.ext filename.ext...". (You may use widlcards in the file names such as "*.txt") The file names will be shown on the screen and you will be given a chance to abort the operation by pressing `n'. If you have the file names correct, press `y' and they will be expunged one at a time, with confirmation messages placed on the screen to reflect this.
If the file is subsequently undeleted and then viewed, it will show blank. You may run this command as many times as you like. The blank files will be replaced with blank files again. I have not tested to see if multiple runnings gain any additional security or not. I doubt it does if a capable file recovery program is used. Some of the deleted file's data is likely to remain untouched and thus may be viewed. If you require a higher level of security, use a commercial file "WIPE" utility.
A PATH MASTER
Have you ever wanted to temporarily add to your Path, but couldn't be bothered to rewrite your AUTOEXEC.bat and then run it or reboot? Here's a way to quickly add one or more directories to your Path statement right from the command line. Afterwards, another batch file will be presented that allows the default Path to be restored.
:: PA.bat :: Adds an Additional Directory to Current Path :: Prevents Duplicate Directories from being Added :: @ECHO OFF IF "%1" == "" GOTO NO-DIR IF NOT EXIST %1\NUL GOTO INVALID SET | FIND "PATH" | FIND "%1" /I > NUL IF ERRORLEVEL 1 GOTO PATH-ADD IF ERRORLEVEL 0 GOTO DUPLICATE :PATH-ADD SET | FIND "DEFAULT" > NUL IF ERRORLEVEL 2 GOTO END IF ERRORLEVEL 1 GOTO DEFAULT IF ERRORLEVEL 0 GOTO PATH-2 :PATH-2 PATH=%1;%PATH% CLS ECHO. ECHO New Path= ECHO. ECHO %PATH% ECHO. GOTO PR-PROMPT :DEFAULT SET DEFAULT-PATH=%PATH% PATH=%1;%PATH% CLS ECHO. ECHO. ECHO New Path= ECHO. ECHO %PATH% ECHO. :PR-PROMPT ECHO. ECHO. ECHO +++++++++++++++++ ECHO "PR" Restores the ECHO Default Path ECHO +++++++++++++++++ ECHO. GOTO END :NO-DIR CLS ECHO. ECHO. ECHO ----------------------- ECHO No Directory Specified. ECHO Please Try Again! ECHO ----------------------- ECHO. GOTO END :INVALID CLS ECHO. ECHO. ECHO ------------------------ ECHO Directory Does Not Exist ECHO Please Try Again! ECHO ---------------------- ECHO. GOTO END :DUPLICATE SET DIRECTORY=%1 CLS ECHO. ECHO. ECHO Directory %DIRECTORY% Already in Path ECHO. ECHO %PATH% ECHO. :END SET DIRECTORY=
First, some "IF" statements check to see if a directory was not included at the command line and if one was, if it does not exist. If either of these are true, the batch file branches to appropriate sections that display messages to the user. Messages created by this batch file will be indented from the left margin to aid in readability. In both cases, the "%1" replaceable will be changed to the name you typed at the command line. The "NUL" is a hidden DOS device that occurs in every directory. If it does not exist, then neither does the directory. This method of directory existence checking doesn't work in all versions of DOS. If it's a problem with your version, eliminate it and the section to which it branches. Alternatively, if you wish to use another method of directory existence checking, then substitute it here. As an example, DR-DOS has the "DIREXIST" condition of its "IF" command.
Next, the DOS "SET" command line is used to see if the directory name typed at the command line is already included in the Path. It does that by piping the output of SET to the DOS "FIND" command. SET, by itself, displays the current environment variables. FIND is then directed to look for the Path statement line. That is turn is piped again through a second FIND command that looks for the directory name. The "/I" switch tells FIND to ignore the case of what you typed. This allows you to type a directory name in upper, lower, or mixed case. The "/I" switch is not needed for FIND to locate "PATH" because DOS always displays the Path variable in upper case. The result of the "FIND" line is tested though DOS Error Levels. The explanation of Error Levels is beyond the scope of this article, but see Exit Codes at this website. Just understand that the results dictate where the batch file goes next.
So, if the directory is found in the Path statement, the batch file is directed to branch to a section that displays a message saying the directory is already included. If this, or either of the previous branches occur, the batch file is directed to end.
Now the real work starts. If all is well, the batch file goes to the "PATH-ADD" section. SET and FIND commands are used again to locate an environment variable called, in full, "DEFAULT-PATH". This would have been created if this batch file had previously been run and the Path had been altered from the default. (This is explained farther on.)
The DOS "IF ERRORLEVEL" testing method is used again to direct the batch file to the appropriate section based on whether FIND has found the "DEFAULT-PATH" environment variable or not, and whether any detrimental error has occurred. In the latter case, the batch file ends.
If it branches to "DEFAULT-PATH", it's because this is the first time the batch file was run since the last bootup, or since the last PR.bat (Path Restore) was issued. (See farther on for PR.bat.) Here, the "DEFAULT-PATH" environment variable is set. It remembers the Path as set in the AUTOEXEC.bat or by the user if it happened to have been set manually at the command line at a previous time.
Next, the actual Path is changed to include the directory you gave at the command line. Your new directory will be placed first. This is handy because you are likely only adding this directory so you can do some immediate work and it will be removed soon thereafter. Having it first in the Path statement, means that you won't have to wait while DOS searches through all the other directories until it reaches this added directory. Thus, its commands will be executed more quickly than if it had been placed last.
The batch file ends by placing two messages on the screen. One tells you the new Path, and thus confirms your addition; the other is one that reminds you that the default Path can be restored by entering "PR". The "DEFAULT-PATH" environment variable remains in memory to enable this. Should you reboot, or lose power and have to restart, the default Path will automatically be reset via the AUTOEXEC.bat's "PATH" statement.
Now, if this batch file has already been run and you want to add another directory to the Path, it will branch to "PATH-2". Here the previously-set PATH variable is updated with the addition of a second directory. Your previous addition will still be there because this batch file has already changed the Path statement to include the last addition. This second directory addition will simply be placed in front of that. You may continue to add directories via this method up to the 127-character Path statement limit, but it's not recommended because of the long searches that might ensue.
The batch file continues as before by displaying the various messages and then ends.
One other thing the file does is to check to see if the directory is already in the Path. Placing it there again would lengthen the search time and bring one closer to the 127-character limit. The "DUPLICATE" section prevents that. It would have been branched to earlier on if the test to see if the given directory was already in the existing Path statement proved true.
Presented now is the Batch File
To Restore the Default Prompt.
:: PR.bat :: Restores the Default Path :: @ECHO OFF IF "%DEFAULT-PATH%" == "" GOTO PATH-OK SET PATH=%DEFAULT-PATH% CLS ECHO. ECHO. ECHO Default Path Restored! ECHO. ECHO %PATH% ECHO. GOTO END :PATH-OK CLS ECHO. ECHO. ECHO ------------------------- ECHO Default Path Already Set ECHO ---------------------- ECHO. ECHO %PATH% ECHO. :END SET DEFAULT-PATH=
This starts by checking to see if the "DEFAULT-PATH" environment variable has been set. If it has not, it means PA.bat has not been run, the computer has been rebooted since it was, or PR.bat has already been run. It then branches to "PATH-OK" and displays a message stating the default Path has already been set and shows that Path. The batch file then ends.
If, however, the "DEFAULT-PATH" environment variable has been set, the
batch file moves on to reset the Path to its original version. A message
says this has been done, the original Path is displayed, and the file ends
by resetting the environment variable to equal nothing to remove it from
All one needs to do is to issue the "PA" batch file name, a space and the new directory that you wish to add to the Path statement. So if you needed to add the Utilities directory on drive `D', it would be "PA D:\UTIL". You may add more directories one at a time via this method, or you may add multiple directories with one command: "PA D:\UTIL;E:\TEST", and so on. Just be sure to place a semi-colon between each directory name and to specify full paths with drive letters, colons, and backslashes. Do not place a space between names you are adding and don't type a semicolon after the last name because the batch file does that for you. At any time, to reset to the default Path, issue "PR".
You may wish to think about using the "Path Add" and "Path Restore" commands in a batch file that starts another program. That way the program will be in the Path while it's running, but be removed immediately afterward.
Note that if you do not include a proper drive syntax, a new (invalid) directory will be added by mistake. Error checking could be included in PA.bat, but it would complicate and lengthen the batch file severely. This is because a lot of mistyped possibilities would have to be covered. Therefore, just be sure that you peruse the new Path as displayed after the batch file ends to be sure the addition has a valid drive letter, colon, and backslash. If it's wrong, issue "PR" and then retype the "PA" batch file name with the corrected directory name you wish to add.
Should anything go wrong, simply reboot to restore the default Path as
written in your AUTOEXEC.bat. If this happens frequently, write a
"Path Default" batch file that issues a new Path statement as written in
the AUTOEXEC.bat. Its main line would read:
@SET PATH=(the exact Path wording as seen in the AE batch file)
ADDING a NOTE to YOUR PROMPT
Having a command line method of typing notes is shown with NOTE.bat in Advanced Batch Files III. However, at times, it might be nice to have an on-screen reminder. This batch file allows a short note to be placed in the prompt so that every time the prompt is displayed, the note will be visible.
:: REMIND.bat :: Places Short Notes into the Command Prompt :: @ECHO OFF IF NOT "%USER-TEXT%" == "" GOTO UPDATE SET DEFAULT PROMPT=%PROMPT% ECHO @SET PROMPT=%%DEFAULT PROMPT%% >: C:\BATCH\RESET.BAT GOTO REMIND-TEXT :UPDATE SET PROMPT=%DEFAULT PROMPT% :REMIND-TEXT ECHO. C:\DOS\XSET /PROMPT " Enter Text to be Reminded: " USER-TEXT ECHO. PROMPT=$_ %USER-TEXT% $_%PROMPT% :END ________
The file begins by checking to see if the "USER-TEXT" variable has been set. If this is the first time the file has been run since the last boot-up, it will not have been set. So the batch file goes to the next line which preserves the current default prompt as "DEFAULT PROMPT".
Next, the file creates another batch file that will be used to reset the prompt and erase the note. The single line is simply redirected to "RESET.bat". Its only purpose is to restore your regular (default) prompt, thus erasing any note you created previously. If there is no note, then running it only "restores" what is already on the screen and no change will result.
Note the double percent signs in that line. They are required for all redirected percent signs. Single ones will be erased during a redirection. So in order to have them survive the redirection, an additional one is required for each original percent sign.
Now the "REMIND-TEXT" section is executed. Blank lines are added before and after the on-screen request for text. That request is placed there by XSET, an update to the DOS "SET" command. Note the quotation marks and spaces. The quote marks are necessary for XSET to do this task. However, I placed the spaces. This is so the request for the reminder text stands out on the command line.
XSET then takes the user's input and places it into an environment variable called "USER-TEXT". This, in turn, is used as part of a new prompt. The new prompt first drops down a line via the `$_'. It then places your note on the screen preceded by leading spaces. Finally, it places your regular (default) prompt on the line underneath, again via using `$_'. Thus, your note will have a blank row above and leading spaces on its line. These are to move the note away from text above and the left margin to make it stand out when the screen is full of text.
Should the batch file be run again, the initial "IF" statement will direct the batch file to the "UPDATE" section. There, the prompt is reset to the default, erasing the previous note. The batch file then runs as before, except placing a new note into the prompt.
Simply type "REMIND" at any DOS prompt. Then add your text. Press "ENTER" and a new prompt appears with your text above it. To change the note, repeat this, but input different text. To erase the note and restore the prompt, enter "RESET".
This is a simple batch file, and as such, there are restrictions. First, you may only type a single line. It may be edited with the Cursor Keys, and HOME, END, etc. keys, but as soon as you hit "ENTER", it will be set and the new prompt will appear.
Since it is using the DOS "PROMPT" command, the total line length must not exceed the maximum allowed prompt length. That includes the default prompt which appears along with the note. This is a minimum of 127 characters, total, but some versions of DOS will allow longer prompts. If you exceed whatever length is allowed, the prompt will not display properly. However, "RESET" will always restore it to the default.
Another restriction is that rebooting will erase the note, as will any programs or batch file that resets the prompt. So be careful if you have an important note.
XSET may be obtained from -xset.tripod.com.
A TASK TIMER
So you have to work on a project and are being paid, or have to bill, by the hour. You need to know the time spent in the computer program used in the project so you have been writing down your start & stop times. Unfortunately, you've been distracted before or during a few of the sessions and have lost track of some of the times. Here's a simple way to have the start & stop time logged each time you enter & leave the program:
It will be assumed that you are using NEOPAINT for a graphics project and that it is in a subdirectory of C:\GRAPHICS.
:: TIMER.bat :: Logs Start and Stop Times of NEOPAINT :: @ECHO OFF C: CD\GRAPHICS\NEOPAINT IF EXIST NP-LOG.TXT GOTO LOG :CREATE ECHO NEOPAINT LOG >: NP-LOG.TXT ECHO. >> NP-LOG.TXT :LOG ECHO Neopaint was started: >> NP-LOG.TXT ECHO. | DATE | FIND "Current" >> NP-LOG.TXT ECHO. | TIME | FIND "Current" >> NP-LOG.TXT NEOPAINT ECHO. >> NP-LOG.TXT ECHO Neopaint was stopped: >> NP-LOG.TXT ECHO. | DATE | FIND "Current" >> NP-LOG.TXT ECHO. | TIME | FIND "Current" >> NP-LOG.TXT ECHO - - - - - - - - >> NP-LOG.TXT ECHO. >> NP-LOG.TXT MORE < NP-LOG.TXT
This file starts by switching to the NEOPAINT directory and then by creating the log text file should one not exist. This step places a title a bit in from the left margin to center it more over the date & time lines. After that, it makes use of the DOS "DATE" and "TIME" commands. As explained with CTULD.bat in Advanced Batch Files, a RETURN keystroke can be sent to the DATE (or TIME) command and then piped to the FIND command. This presses ENTER for you and locates the line with the current DATE (or TIME).
(Users of this batch file should be aware that
it was based on MS-DOS. Those using other DOS
manufacturers or using DOS under Windows will
have to alter the batch file to match what
their DATE commands output.)
For this batch file, the output is passed to a log file to document when NEOPAINT was started, and again after exiting the program, to document when it was stopped. Of course, NEOPAINT is also started by this batch file. We continue by having the batch file place a dashed and a blank line at the end of each session as a separator for the next session's log dates & times.
Finally, the log file is displayed on screen to confirm the log operation. The DOS "MORE" command displays the information a screen at a time. If the file grows to be large and you wish to see only the last page of entries, then substitute this line:
This will work just fine, but the date & time lines will also contain the phrase "The Current Date (Time) is". We could get rid of this and single out the dates and times, as was done in CTULD.bat, but that is a longer process and requires a number of additional files be created. However, using XSET, as seen farther back on this page in BU.bat, will reduce the process to just a few lines. The same technique is used in the improved NOTE.bat as seen in Advanced Batch Files III page.
:: TIMER.bat (Improved) :: Logs Start and Stop Times of NEOPAINT :: @ECHO OFF C: CD\GRAPHICS\NEOPAINT IF EXIST NP-LOG.TXT GOTO LOG :CREATE ECHO NEOPAINT LOG >: NP-LOG.TXT ECHO. >> NP-LOG.TXT :LOG C:\DOS\XSET CUR-DATE DATE C:\DOS\XSET CUR-TIME TIME ECHO Neopaint was started: >> NP-LOG.TXT ECHO Date: %CUR-DATE% >> NP-LOG.TXT ECHO Time: %CUR-TIME% >> NP-LOG.TXT NEOPAINT ECHO. >> NP-LOG.TXT C:\DOS\XSET CUR-DATE DATE C:\DOS\XSET CUR-TIME TIME ECHO Neopaint was Stopped: >> NP-LOG.TXT ECHO Date: %CUR-DATE% >> NP-LOG.TXT ECHO Time: %CUR-TIME% >> NP-LOG.TXT ECHO - - - - - - - - >> NP-LOG.TXT ECHO. >> NP-LOG.TXT MORE < NP-LOG.TXT
This version uses XSET to place into the DOS environment the dates and
times the program was started and stopped. Using this method gives a cleaner
looking log. Typically, it will display as:
NEOPAINT LOG Neopaint was started: Date: 10-11-03 Time: 10:33:53 Neopaint was Stopped: Date: 10-11-03 Time: 10:33:57 _ _ _ _ _ _ _ _
The rest of the file runs as in the first version. Realise this method
of logging program times does not take into account if you leave the
program running and then take a games break, nor if you run the program
during your project for another purpose. While DOS batch files can't
monitor when you are goofing off, they can be used to log just your
project. Simply name the batch file something like NP-WORK.bat and only
use that batch file to start NEOPAINT when you are working on your
project. For other times, start NEOPAINT as you ordinarily would.
XSET may be obtained from -xset.tripod.com.
A BACKUP-to-FLOPPY ROUTINE
I often do web page work at my place of business and wish to take the files home, partly as a backup, but also so that I will have my web pages available on my home computer. I could use a flashdrive, but the files are small enough to easily fit on a floppy, and since I prefer to compress (zip) them, a zipped file transfers plenty fast to a floppy disc. The main reason for using zip files though, is that I have a number of batch files that expand specific .zip files, sort them, and send them to the appropriate directories on my home computer. The .zip file is then deleted. This second operation is all done in one step. I may present that batch file here in the future, but it is quite complicated.
Here is one of the batch files I use on files sent to my work computer's UPLOAD directory. The one presented here is called by the "UPLOAD" batch file to run in tandem so that it also compresses the same files and sends a backup .zip file to my `B' floppy drive. The version presented here will allow creation of the `B' drive .zip file from all or selected files in any directory.
Note that you can substitute a USB flash-drive letter and remove the `-&' to zip to that drive. I use flashdrives but find that, for this purpose, floppies are actually faster! This is because the compressed files are small (typically under 50 kB) and the mounting time for a flashdrive is longer than for a floppy drive which is automatically mounted when the computer is booted. Plus, I run a super cache that will write to the floppy while I do other work, so even when it might take longer, I rarely notice because I can continue to work elsewhere.
It will be assumed that you are using PKZIP which is located in a "PKZIP" directory under a "UTIL" directory on the `C' drive.
:: ZTB.bat :: Makes a Specified .zip File on the B Drive From :: All or Up to 5 Specified Files :: Keeps Directory Information :: Spans Discs as Necessary :: @ECHO OFF IF "%1" == "" GOTO NO-FILE IF "%2" == "" GOTO ZIP-ALL IF NOT "%2" == "" GOTO ZIP-SPEC :ZIP-SPEC SET PKTMP=C:\TEMP C:\UTIL\PKZIP\PKZIP -& -rp b:\%1 %2 %3 %4 %5 %6 GOTO END :ZIP-ALL SET PKTMP=C:\TEMP C:\UTIL\PKZIP\PKZIP -& -rp b:\%1 *.* GOTO END :NO-FILE ECHO. ECHO No ZIP File Name Specified! :END ECHO. CALL C:\BATCH\DR B: SET PKTMP= ________
This starts out with three "IF" lines. The first determines if you have specified a .zip file name. If not, a prompt appears stating the same. The next two determine if you have placed one or more files names after the .zip name. If you have not, the batch file jumps to the "ZIP-ALL" label and all files in the directory and below will be compressed.
If file names are given, the file goes to the "ZIP-SPEC" label which is for specific file names. This line is actually not needed because the file will automatically go to "ZIP-SPEC" if the first two "IF" statements are false. It's included here for clarity.
Each of the PKZIP sections first sets a TEMP directory in which PKZIP is to work. If you have a RAM drive, point this line to it for faster execution of the ZIP process. Next, the actual compression is done. Both sections are set to span discs via the "-&" switch, should the .zip file be too large for one floppy. As well, subdirectory Path information and any files contained therein will be kept during compression via the "-rp" switch. That stands for "recurse" and "Path". When the file is later uncompressed, the directory and file structure will be recreated in the directory in which the unzipping occurs.
If you don't want this, you may remove the "-rp" switch. This will only compress the files in the current directory. On the other hand, if you do wish to have the files in the directory and its subdirectories be placed all in one directory, simply use "-r" by itself. When you uncompress a .zip file done in this manner, all files from the originally-selected parent directory and its sub directories will be placed into one directory.
Alternatively, If you want the choice during uncompression, use "-rp" during compression and include "-d" during uncompression to create the subdirectories with their appropriate files, or do not use "-d" to have all the files placed into the same directory.
Be aware, these switches must be lower case. Using upper case letters often means alternative uses. As an example, using "-rP", will recurse the files; plus their *original* directories will be created regardless of in which directory the file is unzipped. That is, that directory structure will be preserved.
Getting back to the explanation of the example batch file, in the "ZIP-SPEC" section, PKZIP can handle up to five names as given on the command line. Add more percent numbers (up tp `%9') if you plan to list more file names in your typical usage.
Finally, the TEMP variable is removed from memory and a directory listing of the `B' drive conforms the operation. As with other examples, you may substitute the DOS "DIR" command for my "DR" batch file.
Simply change to the desired directory and issue "ZTB (.zip file name)". So if you have .html files, the command might be "ZTB HTML". You will then see PKZIP do its work and then see a directory listing showing a file called "B:\HTML".
For my actual usage, I have this file modified to deal with html files exclusively. I then have a series of batch files based on this that make specific-to-purpose .zip files. As an example, I have one that will compress the html files that deal with this DOS website. Thus, a file called "DOS.zip" is created. I also have a more sophisticated version that zips only changed files to my UPLOAD directory. This is in preparation to send any new versions of my webpage files to my server. That batch file version will also zip them to my `B' drive floppy to take home with me as an off-site backup.
A SELF-EXTRACTING COMPRESSION ROUTINE
You want to give some files to a friend, so to save time & space, you give her a .zip file. Or, you want to take some files to your friend's house and put them on her computer. For the reasons above, you take a .zip file. However, in order to uncompress the files, she will have to have PKZIP or an equivalent on her computer, plus know where it is and how to use it. It is much better to have a file that can unzip itself.
Here is a batch file to do that for you. This assumes that you have PKZIP which is located in a "PKZIP" directory under a "UTIL" directory, and that both directories are located on the `C' drive.
:: ZTE.bat :: Makes an Executable from All or Specified .zip Files :: in the Current Directory :: @ECHO OFF IF "%1" == "" GOTO EXE-ALL IF NOT "%1" == "" GOTO EXE-SPEC :EXE-ALL SET PKTMP=C:\TEMP FOR %%Z IN (*.ZIP) DO C:\UTIL\PKZIP\ZIP2EXE %%Z GOTO END :EXE-SPEC SET PKTMP=C:\TEMP C:\UTIL\PKZIP\ZIP2EXE .\%1.ZIP :END ECHO. CALL C:\BATCH\DR.BAT SET PKTMP= ________
This starts out with two "IF" lines. If no zip file is specified on the command line by you, then .exe files will be made from all.zip files in the current directory -- one for each .zip file. If a .zip file name is specified, then only it will have an .exe file produced. This is done by having DOS check to see if a parameter was typed or not and then having the batch file go to the appropriate PKZIP section.
In both sections, a TEMP directory is set in which PK may do its work. If you have a RAM drive set up, be sure to point PK to that TEMP directory. The operation operates much faster on a RAM drive. Both sections also use PKWARE's "ZIP2EXE" feature. In the "EXE-ALL" section, a DOS FOR-IN-DO (FOR) command is used. It means that "FOR each .zip File listed INside the Brackets, DO the following command". Since a wild-card name was used (*.zip), the action is taken on each .zip file in the current directory. DOS directs PKZIP to make an .exe file with the same name as each .zip file it finds.
If a file name is given, the batch file goes to the "EXE-SPEC" label. DOS then directs PKZIP to make an .exe file from the zip file name you typed at the command line.
The file finishes by removing PK's TEMP directory specification from memory and then giving a directory listing to show the success of the operation.
After making a zip file in any directory, go to that directory and simply type "ZTE" and an .exe file will appear. If there is more than one .zip file and you only want one of them to have an .exe version, type "ZTE (file name)". Do not type the ".zip" extension; the batch file does it for you.
Additional advanced files are in
Advanced Batch Files 3