(Image: DOS Logo)


Doctor
DOS
Betamax's

ADVANCED BATCH FILES
I

******




Advanced I Preliminary
Read This First!


(Skip to the Batch Files)


Batch Files Table of Contents
CDS.bat
Change Directory
Sideways


CTULD.bat
Copy to UPLOAD
by Date


DBF.bat
Directory of the
`B' Drive with
an Optional Format


DELE.bat
(Improved)
Delete All Files Except...

DRTD.bat
List
Today's Files


EAE.bat
Edit
AUTOEXEC.bat


ECS.bat
Edit
CONFIG.sys


RETURN.bat
Return to a
Tagged Directory


SDEL.bat
(Improved)
Safely
Delete Files


THOUGHT.bat
Displays a
Thought of the Day


TOP.bat
Go to Any Drive's
Root Directory


UPDATE.bat
Updates a Directory
with the Latest Files





 

  PRELIMINARY

    This is the first page of advanced batch file examples. These are more intricate than the previous examples. As before, the title remarks should suffice so you'll understand their operation (although some may be preceded by a syntax example). The more ambiguous lines have notes to the side. They 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, read Batch File Basics regarding the techniques for writing batch files. Note that because this is an advanced page and you should have read the previous batch file articles at this site, that not every little thing will be explained.

    Again, remember, the "DR" command is a batch file that runs the Color Directory program I use. You may substitute DOS' "DIR" command with its switches set to your preferences.

    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.



 

  THE BATCH FILES

 
*    CDS.bat

:: CDS.BAT
:: Changes to an Adjacent Directory on the Same or Higher Level
:: Displays the Results
::
@ECHO OFF

IF "%1" == "1" GOTO LEVEL-1
IF "%1" == "2" GOTO LEVEL-2
IF "%1" == "3" GOTO LEVEL-3
IF NOT "%1" == "1" GOTO LEVEL-1A

:LEVEL-1
CD ..\%2
GOTO END

:LEVEL-2
CD ..\..\%2
GOTO END

:LEVEL-3
CD ..\..\..\%2
GOTO END

:LEVEL-1A
CD ..\%1

:END
C:\BATCH\DR

Explanation

    The file first determines if you used a number at the command line and what that number might be. The results branch to one of the LEVEL labels where the appropriate CD (Change Directory) command is issued. Each " ..\ " represents the next-level-up (parent) directory. Subsequent additions represent the grandparent, great grandparent, and so on, directories. Try it yourself at the command line from any sub-directory. "CD ..\" will take you up one level.


Usage

    This file allows one to change to a directory adjacent to the current one. That is, if the directory one level up is PARENT-1 and you are in CHILD-1, by issuing "CDS CHILD-2" or "CDS 1 CHILD-2", you will be whisked sideways into that directory, and a list of files will appear. Note that this batch file allows one to give no number or a number `1'. Either will take you to an adjacent sub-directory of the directory one level up.

    Here is a display of that structure to help you visualise this better:


Level 3                            GRANDPARENT
                         -------------------------------
                         |                             |
Level 2               PARENT-1                      PARENT-1A
                   -------------                 -------------
                   |           |                 |           |
Level 1         CHILD-1     CHILD-2           CHILD-1A    CHILD-2A

    You may also go to an adjacent directory two or three levels higher by including a number `2' or `3' on the command line. So, let's say you are back in CHILD-1. The next level up is still PARENT-1. Adjacent to it on the same level is PARENT-1A, and above both PARENT directories is GRANDPARENT. To get to CHILD-1A under PARENT-1A, issue "CDS 2 PARENT-1A\CHILD-1A". You may do the same thing with the directory above GRANDPARENT by using the number `3'.

    Note that the name "PARENT-1A" exceeds 8 characters. It is just used here to better represent that directory so as to keep it straight with the other directories shown. If your DOS is not long file name capable, this directory name would get truncated to "PARENT-1". As such, it could not be created because there is already a directory with that name. Again, this was just done here to help you comprehend this example. Of course, in actuality, you will be typing the names of directories on your own system.

    When you use this batch file, don't forget the space on either side of any number you use at the command line. If you have a good visual idea of your directory tree, you may add lines to the batch file for more levels if you wish.


Directory Display?

    For those of you thinking about having the batch file show the directory structure, I tried that but found it to be confusing if there were a lot of directories to display. If you wish to try it, add the following lines after each "LEVEL" label:

TREE .. | MORE
PAUSE

    After "TREE", enter the same number of dots and backslashes as are after the succeeding "CD" line. When the file runs, a directory tree will be displayed for the number of levels you indicate on the command line (1 -3). The batch file will then pause to allow you to view the last screen of TREE. After TREE finishes, pressing any key will then take you to the directory you first typed on the command line. If you typed the wrong one, simply issue "CONTROL-C" to stop the batch file. Then run it again with the proper directory name.

    I also found that having the tree displayed was annoying every time I wanted to use this batch file. A better method would be to have the batch file display the directories only when you needed, and then allow you to enter the directory to which you might wish to go. Perhaps I'll write that version and add it here in the future.

    This sort of changing method can be tedious if you have a complicated directory structure and/or long directory names. It can be eased with an autocompletion utility such as that provided by Toddy or 4DOS, but a better method is to use an autochanger such as Directory Maven. Links to these programs may be found at the DOS Websites Directory.



 

AUTOMATIC COPYING BY DATE

    Here's the scenario: You work all day on some web page files in a given directory and you wish to copy just the modified ones to your UPLOAD directory to transfer them on line to your server. Unfortunately though, by the end of the day, you have forgotten the exact ones upon which you worked.

    You could issue a DIR /O:D or XDIR /Tcommand to sort by date, note which files have today's date, then issue copy commands for each, but that's a lot of typing. You could open up a file manager, hunt through the directory's file list and tag (mark) each file having today's date. Then you'd copy the marked files to the UPLOAD directory... but why bother with such tedium? What would happen if you wanted files from the last few days copied? That adds an extra element of complexity. As always, efficient DOS can do this for you automatically.

    This next batch file uses the DOS environment to hold the value of the current date. This is called an "environment variable". That's because the variable may have different values at different times - in this case, the differing value will be the changing date on a given day. (The "environment" is an area of memory which, in part, holds various parameters to which programs refer as a guide to how they should operate. See DOS Variables for more information.) The batch file then uses this current-date variable in a fairly typical XCOPY operation to copy only today's files, or alternatively, those from a few days, weeks, or more ago, on up until & including today. This is very slick; it saves a lot of typing, file perusing, note taking, and best of all - it keeps you at the efficient command line instead of opening up a graphical file manager and forcing you to do work.

    Realise that this example was designed for those using DOS versions without a built-in date variable. See "Improvements" for further discussion.


*    CTULD.bat
Syntax: CTULD (Optional Date)
:: CTULD.bat
:: Copies Files Modified or Created Today
::  to the Upload Directory, or Copies
::   from the Specified Date Forward
::
@ECHO OFF
                                      If no Date is Given, Today's
IF "%1" == "" GOTO COPY-TODAY           Files will be Copied
IF NOT "%1" == "" GOTO COPY-DATE      Otherwise, Files will be Copied
                                        Forward from the Date Typed

:COPY-TODAY                                   (See Text, Below)
ECHO. | DATE | FIND /I "Current" >: C:\BATCH\CUR-DATE.BAT
ECHO @SET CUR-DATE=%%4 >: C:\BATCH\CURRENT.BAT
CALL C:\BATCH\CUR-DATE.BAT

XCOPY *.* C:\UPLOAD /D:%CUR-DATE% > NUL  Copies Files based on
                                         Today's Date
                                         ("NUL" Hides Screen Messages)
GOTO END

:COPY-DATE                                 Copies Files based on
XCOPY *.* C:\UPLOAD /D:%1                    The Date Given at the
                                             Command Line
:END
ECHO.                                      Separates the Listing
CALL C:\BATCH\DR.BAT C:\UPLOAD             Gives a Listing for the
                                             UPLOAD Directory to
                                             Show the Operation's Success

SET CUR-DATE=                              Removes the Date Variable
                                             From the Environment

DEL CUR-DATE.BAT                           Deletes the
DEL CURRENT.BAT                              Temporary Batch Files
                                ________


Explanation

 Remember: This DATE method and explanation
is for those using a DOS version that does not
include a built-in DATE variable. Those with one
built in may skip to the: XCOPY section.

    For the "COPY-DATE" section, a partial explanation of what happens may be seen by typing "DATE" at the command line. DOS gives the current date (assuming you have correctly set the date and that it has been maintained by the computer's CMOS battery). Then, DOS also asks you for a new date. This is so that a user may type in a given date, which is normally the current one. To keep this current date, hit "ENTER". The trick here in this batch file example is to have it hit "Enter" for you and also to isolate the current date and make it an environment variable. This variable may then be used for the XCOPY operation.

    In the batch file, the "ECHO." at the start of the "COPY-DATE" section sends a carriage return ("ENTER") to the DATE command, leaving the current date unchanged, as you just did when you ran "DATE" from the command line. The DATE command is then piped to the FIND command, which is asked to locate the line containing the word "Current". That solitary line in turn is sent to a file called "CUR-DATE.bat", which is created by this (CTULD) batch file. The text sent to the "CUR-DATE.bat" file reads "Current Date is (day) (date)". Note that the fourth parameter (word) after "Current", matches the date whenever the batch file is run.

    For the next line, using the DOS "SET" command, a variable called "CUR-DATE" is made from the fourth parameter (designated `%%4'). This is sent to another created file called "CURRENT.bat".

Now everything is in place, so let's review:

    We have one file called "CUR-DATE.bat" that contains a single line reading "Current Date is (day) (date)". This is called by CTULD.bat. Being a batch file, DOS tries to run CUR-DATE.bat. Since the first word in that is "Current", DOS believes there is a program or file able to be executed called "Current". Well, guess what? A batch file called "Current" was just created.

    So DOS in turn runs that, because DOS sees "Current" to be a batch file name and the rest of the words to be parameters for that command. The fourth parameter is the current date. CURRENT.BAT executes its only line which says to place this fourth parameter into the environment as "CUR-DATE".

    Now, when CUR-DATE finishes, control is returned to CTULD.bat, which runs the XCOPY line that has a variable in it now being defined as the current date.

 

    When the XCOPY line is run, the current date will be substituted for "CUR-DATE" every time, and thus XCOPY will copy files to the UPLOAD directory created or modified only on the day it is run. Slick, huh? Since these sub-files are created every time CTULD.bat is run, the XCOPY date parameter will always be the current date. Even if the files already exist, they will be overwritten with the latest date information. Regardless of when you run CTULD.bat, it always will be today's files that will be copied, unless you fill in a command line date parameter. In that case, control is transferred to the "COPY-DATE" section.

    For the "COPY-DATE" section, DOS simply substitutes the date you type on the command line and runs XCOPY based on that date. Thus if you type "CTULD (last week's date), DOS will copy files to the UPLOAD directory on and forward of the date you typed at the command line. Remember to type the date in the same format as that which is recognised by your computer for your country.

(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.)



Improvements

    This file can be shortened by using updated DOS commands or by using a version of DOS that includes the `%DATE%' variable built in. For those using DOS versions without the latter, one method is to get an update of the "SET" command, called "XSET". It can set a date variable with just one line of code without the extra files or even the piping, as was done in the above batch file example. This, and many other capabilities are built into the XSET command.

    If used in the above example, a one-line XSET command can set "CUR-DATE", with the next line immediately being the XCOPY-by-date command. It shortens and simplifies the batch file. See DRTD.bat, farther on, for an example of the XSET date technique.

    Another, even shorter method is done via an update to "XCOPY" called "XXCOPY". It can do either operation using just one line:

XXCOPY *.* /DA:%1

    One would go to the directory in which the command is to be issued, and enter "CTULD ." for today's files, or enter "CTULD (date)" to copy files on, or after, the given date. Excluding a title and comments, this method reduces the CTULD batch file to just one line!


    Links to these updated commands may seen in the:
DOS Websites Directory.

 
*       DBF.bat
(Requires DOS 6 or Newer)

    Although floppy discs have given way to flashdrives, they are still used by many - especially when dealing with older systems. This batch file allows one to get a directory listing of a floppy disc and then prompts to format it or not. This is handy if you need a blank disc but want to check first to see if there are any files on it you might want.

    Regarding flashdrives, this batch file could be modified to format one by substituting its drive letter for the letter `B' used here. Of course, before running it, USB drivers must be loaded and the flashdrive mounted (recognised).

    It will be assumed that the `B' drive is to be used and that the floppy drive and blank disc size is 1.44 megabytes. Change these if yours differ.

:: DBF.bat
:: Shows Directory of `B' Drive
:: Prompts to Do a Full or Quick Format or No Format
:: If Quick Format is Chosen, Does Not Save Unformat Information
::
@ECHO OFF
CLS

CALL C:\BATCH\DR B:\
ECHO.
ECHO.

ECHO                            Full Format B Drive?
ECHO.
ECHO                             Press `F' to Format
ECHO.
ECHO.
ECHO                            Quick Format B Drive?
ECHO.
ECHO                           Press `Q' to Quick Format
ECHO.
ECHO.
ECHO                           Press "Escape" to Cancel
ECHO.

C:\DOS\CHOICE /C:FQ<- /N > NUL

IF ERRORLEVEL 3 GOTO END
IF ERRORLEVEL 2 FORMAT B: /Q /U
IF ERRORLEVEL 1 FORMAT B:

: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 an "Escape" character by pressing ^V first.)

                                 ________


Explanation

    After the header information, the batch file clears the screen and displays a directory listing of the `B' drive so you see what, if any, files are on the drive. You may substitute the DOS "DIR" command here with your preferences.

    Next, some choices are placed on the screen with blank lines in between for readability purposes. They are also indented from the left margin to make then stand out on the DOS screen. After that is the CHOICE command. The choices (F, Q, and Escape) are listed after the "/C" (Choice) switch. The "/N" (No Display) switch hides CHOICE's display of these letters, while the "> NUL" directs any additional prompts to be hidden.

    After this are ERRORLEVEL statements. These determine which key is pressed by the user and then to act accordingly. I won't get into how these work because it is beyond the scope of this batch file example page. (See DOS Exit Codes.) You can see that each ERRORLEVEL statement corresponds to one of the possible keys and that each has a command after it. Thus, pressing "ESCAPE" tells the batch file to go to the end, which means the disc will not be formatted. The other two ERRORLEVEL statements direct that the disc be either fully formatted or be quick formatted.



 
*       DELE.bat (Improved)

    This is an improved version of the DELE.bat which was presented in the basic Batch File Examples. It allows multiple files of differing names to be specified for exclusion from deletion. All else in the current directory will be deleted except for files with certain attributes.


:: DELE.bat
:: Deletes Current Directory Entries Except for Specified Files
:: Wildcards (* and ?) may be Used in File Names
::  (Hidden, System, and Read-Only Files are Not Affected)
::
@ECHO OFF

IF "%1" == "" GOTO END          Stops the Batch File if no File
                                   Names are Given.

MD SAVE                         Makes a Temporary "SAVE" Directory.

:MOVE-FILES
XCOPY %1 SAVE > NUL              Copies the First Specified File
SHIFT                            Uses the "SHIFT" Command to move
IF "%1" == "" GOTO FILES-DELETE   each Specified File name to the
GOTO MOVE-FILES                   "%1" Position after it copies that
                                  Specified File to the "SAVE"
                                  Directory until none are left.
:FILES-DELETE
ECHO Y | DEL . > NUL             Deletes all Files in the Current
                                    Directory, showing no Prompts.
MOVE SAVE\*.* . > NUL            Returns Excepted File(s) to the
                                    Current Directory.
RD SAVE                             Removes "SAVE" Directory and
DR                                  Displays the Results of the
                                       Operation.

:END


 
*       DRTD.bat

:: DRTD.bat
:: Lists Files Made or Modified Today
::      In the Current or All Directories
::
@ECHO OFF

C:\DOS\XSET CUR-DATE DATE MM-DD-YY

IF "%1" == "\" GOTO LIST-ALL

:LIST-CUR
DIR *.* | Find "%CUR-DATE%" | MORE
GOTO END

:LIST-ALL
DIR \*.* /S | Find "%CUR-DATE%" | MORE

:END
SET CUR-DATE=

Explanation

    The file starts by using the updated DOS command, "XSET" to place the current date into the environment variable "CUR-DATE". It is in the typical format the DOS "DIR" command shows for file dates. If you have set a different format, alter the date `m-d-y' letters in the batch file to match. It is also assumed that XSET is in the C:\DOS directory.

    Next, an "IF" statement determines if you wish to show today's created or modified files from the current directory only, or those from the entire current drive. A "drive" decision made here directs the batch file to the "LIST-ALL" section. If no `\' parameter is given at the command line, the GOTO directive is ignored and the next line is executed to show today's files from the current directory only.

    In either section, DIR is used to get a list of files. This is piped (passed) to the FIND command. FIND looks for lines with today's date and displays them. Should the screen fill, the MORE command will present the list a screen at a time.

    The batch file ends by removing the CUR-DATE variable from memory by setting it to equal nothing.

See here for a link to XSET: DOS Websites Directory.



Usage

    Simply enter DRTD to get a list of files made or modified today in the current directory. To find all of today's files on the entire current drive, enter "DRTD \".



 
*       EAE.bat
(Requires DOS 6 or Newer)

:: EAE.bat
:: Edits "Autoexec.bat"
:: Prompts to run Autoexec or 
::      Return to the DOS Command Line
::
@ECHO OFF

C:
EDIT C:\AUTOEXEC.bat                     Loads AE into DOS' "EDIT"

ECHO.
ECHO    Run "Autoexec.Bat" ? Press: `R'.        
ECHO.                                    Places choices on to
ECHO    To Cancel,  Press: `Escape'        the screen with spacing.
ECHO.

CHOICE /C:R<- /N > NUL             DOS 6's "Choice" command.
IF ERRORLEVEL 2 GOTO END                 Determines which key has
IF ERRORLEVEL 1 GOTO RUN                  been pressed and decides
GOTO END                                  the course of action.

:RUN
C:\AUTOEXEC.BAT

: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.)



 
*       ECS.bat
(Requires DOS 6 or Newer)

:: ECS.bat
:: Edits the Config.Sys File
:: Prompts to Reboot or Not
::
@ECHO OFF

EDIT C:\CONFIG.SYS                       Loads CS into DOS' "EDIT"

ECHO.
ECHO    Reboot Computer? Press: `R'.          
ECHO.                                    Places choices on to
ECHO    To Cancel,  Press: `Escape'          the screen with spacing.
ECHO.

CHOICE /C:R<- /N > NUL             DOS 6's "Choice" command.
IF ERRORLEVEL 2 GOTO END                 Determines which key has
IF ERRORLEVEL 1 GOTO REBOOT               been pressed and decides
GOTO END                                   the course of action.

:REBOOT                                       
C:\UTIL\WARMBOOT.COM                        See below.

: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.)

                                 ________


WARMBOOT.com

    This is a debug program that I keep in a UTIL (Utility) directory. You will have to change the path in the above batch file, if you decide to store it elsewhere.

Download  WARMBOOT.com.

    Note, that the Reboot option should not be used if you are running any other program. Thus, be sure Windows, DOS SHELL, or any task switching program is shut down, and that you are not shelled out of any other application, before selecting the boot option of this batch file.



 

Directory Tag & Return

    This batch file requires one text file and two batch files to operate. The second batch file is created by the first, which is the one you'll run from the command line when you wish to return to the tagged directory. This combination allows one to tag a directory so that one may return to it at any time, including after a reboot. It may also be included in any batch file that starts a program after which you wish to return to the directory from before you ran the program. An explanation follows "RT.bat". Afterwards, are two improved versions, including an extremely simplified one.


First, begin by creating or copying
the following, beginning with the
double colon lines:

*    RT.txt
:: RT.txt
:: Used with RT.BAT to Return to Tagged Directory
::
@ECHO OFF

CLS
CD(Space)

    Note that the "(Space)" above should not be typed. Simply be sure there is a space after the "CD". As well, do not press "ENTER" after this line. Save this as "RT.txt" in your BATCH directory.

    Be aware that this file should be typed in a text editor that does not allow the cursor to drop below the last line. Otherwise, it will insert a carriage return and the batch file will not work. To test for this, when you type the last line, do not press "ENTER". See if the cursor can be made to drop below this line by pressing the "Down Arrow" key. If it drops, expect that you may have a problem.

    An alternative is to use the "COPY CON" method right from the DOS prompt. Simply go to your BATCH directory and enter "COPY CON RT.TXT" at the command line. Then type the following, pressing "ENTER" after each line:

:: RT.txt
:: Used with RT.BAT to Return to Tagged Directory
::
@ECHO OFF

CLS
CD ^Z

    Be sure to include the space following "CD" and press "Control-Z" immediately after. Hit "ENTER" to exit, and your file will be made. If you cannot get this to work by any method, e-mail me and I will send you a copy of the required text file.



    Now make or copy the following:

*     RT.bat
:: RT.bat
:: Tags the Current Directory
::
@ECHO OFF

COPY C:\BATCH\RT.TXT C:\BATCH\RTT.BAT /Y > NUL

CLS
ECHO.
ECHO     Ready to Return to
ECHO    the Current Directory
ECHO.

CD >> C:\BATCH\RTT.BAT

Usage

    To use this batch file, when you are in a directory to which you wish to return, press "RT, Enter". The screen will clear and the message "Ready to Return to the Current Directory" appears. Now do whatever you want: Start and work within a program, do DOS work, even reboot. When you wish to return to the tagged directory, enter "RTT". You'll be whisked back!


Explanation

    "RT.bat" (Return-Tag.bat) works by creating the file "RTT.bat" (Return-To.bat), containing the main line of "CD  ". It gets this information from "RT.txt" and places it into a new copy of "RTT.Bat", even if "RTT.bat already exists. This is where the "/Y" comes in. It answers "Yes" to the prompt regarding over-writing an existing file so you won't have to every time.

    "RT.bat" continues by placing a message on the screen alerting the user that the directory has been tagged. Then it appends the current directory to the end of the "CD " line via the double ">". The line then reads "CD (tagged directory)". ("CD" by itself displays the current directory and path. Try it yourself at the command line.)

    Since all this is placed into a batch file called "RTT.bat", when you enter "RTT", it changes to the tagged directory. Plus, because it is written to the hard drive, it survives a reboot.

Note this does not work if you tag a
directory on one drive and attempt to
to return to it from another drive.
Simply switch to the tagged directory's
drive first, then issue the "RTT" command.


    This is a simple setup and is VERY powerful, but I crave even MORE power. Therefore, I have assigned "RT" and "RTT" to function keys F11 and F12. Now, I am one keystroke away from tagging a directory and only one away again from returning to it.
    It's very impressive to GUI users that are not used to DOS' blinding speed in situations where you have programmed events into batch files *and* assigned the batch files to function keys. Also, to wow them further, I have all my batch files loaded on to a RAM drive. Since they are always in memory, they are zippy, zippy, zippy! See DOS Tips for more such improvements.



I also have two other versions of this setup. They are
more powerful, and the last is also much simplified.
Both allow one to return to the tagged directory from
anywhere in DOS, regardless of the drive.
Each is presented here:


RETURN.bat
  (Improved)

    The improved version requires two text files, two batch files and a utility to operate. As with the previous example, the second batch file is created by the first. This combination allows one to tag a directory so that it may be returned to at any time, still including after a reboot, but now from anywhere in DOS, even from another drive. Notes follow each section, with a full explanation given at the end, including the "DRIVE-IS" utility.


First, begin by creating or copying
the following, beginning with the
double colon lines:

*    HOME.txt
:: HOME.txt
:: Used With Home.bat
::
@ECHO OFF
(Blank Line)
CLS

    Note the blank line. Do not type those words; simply leave a blank line.



*    SAVE-DIR.txt
CD(Space)

    Note that the word "(Space)" should not be typed, nor should you press "ENTER" after this line. Simply be sure there is a space after the "CD" and that it is the last line of the file. Save both text files in your BATCH directory.

    As discussed farther back, this file should be typed in a text editor that does not allow the cursor to drop below the last line. Otherwise, it will insert a carriage return and the batch file will not work. Should this be a problem, see the previous version of the batch file for a test, and methods to overcome this.



    Finally, make or copy the following:


*    SAVE-DIR.bat
:: SAVE-DIR.bat (Improved)
:: Remembers the Current Drive and Directory
::
@ECHO OFF

COPY C:\BATCH\HOME.TXT C:\BATCH\HOME.BAT /Y > NUL
C:\UTIL\DRIVE-IS >> C:\BATCH\HOME.BAT

TYPE C:\BATCH\SAVE-DIR.TXT >> C:\BATCH\HOME.BAT
CD >> C:\BATCH\HOME.BAT

CLS
ECHO.
ECHO  Ready to Return to
ECHO the Current Directory
ECHO.

How it Works

    SAVE-DIR.bat works by first creating HOME.bat. It does that by copying the lines in HOME.txt to HOME.bat. Next, it uses DRIVE-IS to insert the current drive letter and a colon on the blank line at the temporary end of HOME.bat. It then appends the "CD  " text in SAVE-DIR.txt to HOME.bat.

    Finally, the batch file issues a "CD" command. This command normally displays the current path & directory at the command prompt. However, here it's redirected to HOME.bat where it is put after the letters "CD" and its succeeding space. These are already in place thanks to them being put there when SAVE-DIR.txt was appended to the file. All three operations are done by DOS' append redirector, ">>".

    So what you end up with is a batch file which main lines read:

CLS
(Drive):
CD (Path\Directory)

    The parentheses will have your tagged drive and directory inserted each time you issue the "Tag" (Save-Dir) command. When you run the HOME batch file, it changes to the drive and directory you had previously tagged. Neat, eh?

    Note that there are other ways of getting the current drive into a batch file, but this is a fast and reliable method. It will also work in many versions of DOS, unlike some other methods. Below is an alternate version of SAVE-DIR.bat which does not rely on DRIVE-IS.com. It too, should work on most versions of DOS. Here, the "VOL" (Volume) command is used to save the current drive letter into a variable in the same manner as the "date" technique seen in CTULD.bat, farther back.


*    SAVE-DIR.bat
:: SAVE-DIR.bat (Alternate)
:: Remembers the Current Drive and Directory
::
@ECHO OFF

COPY HOME.TXT C:\BATCH\HOME.BAT /Y > NUL
VOL | FIND "Volume in" > C:\BATCH\TEMP.BAT
ECHO @SET CUR-DRV=%%3: > C:\BATCH\VOLUME.BAT
CALL TEMP.BAT

ECHO %CUR-DRV% >> C:\BATCH\HOME.BAT
TYPE SAVE-DIR.TXT >> C:\BATCH\HOME.BAT
CD >> C:\BATCH\HOME.BAT

CLS
ECHO.
ECHO  Ready to Return to
ECHO the Current Directory
ECHO.

DEL C:\BATCH\TEMP.BAT
DEL C:\BATCH\VOLUME.BAT
SET CUR-DRV=

    In the final version of this batch file, farther on, is another method that can also work well under various DOS versions.

    Each time you use it, SAVE-DIR.bat makes a new HOME.bat by overwriting the old. To eliminate the prompt associated with overwriting a "/Y" is used. It tells DOS to overwrite without prompting. The "NUL" is used to keep the screen clean. Anything sent to NUL is not echoed (displayed) on the screen, so you don't see "One file(s) copied".


DRIVE-IS.com

    DRIVE-IS.com is a compiled debug script.

Download  DRIVE-IS.com and place it in a C:\UTIL (Utilities) directory.


Usage

    To use this batch file, when you are in a directory to which you wish to return, enter "Save-Dir". The screen will clear and the message "Ready to Return to Current Directory" appears. Now do whatever you want: Start and work within a program, do DOS work, switch drives, even reboot. When you wish to return to the tagged directory, enter "Home". You'll be whisked back! You may also shell out of a program and use this to go to the tagged directory. Then, typing "EXIT" takes you back into your application.

    In use, "Save-Dir" and "Home" are too long to type, so either shorten the names, or better yet, assign the batch files to a function keys. One key will tag the drive & directory, the other will return you. I use F11 and F12.



RETURN.bat
 (Simplified)

    As I like to be "Mr. Milliseconds", I am always looking for ways to shorten batch files in order to have them run faster and also to simplify them. Here is a final version of RETURN.bat. It uses an update to the DOS "SET" command called "XSET". In only two steps, this places the current drive & directory into environment variables with no text files or debug utility required.


*    SAVE-DIR.bat
:: Save-DIR.bat (Simplified)
:: Remembers the Current Drive and Directory
::
@ECHO OFF

ECHO :: Home.bat > C:\BATCH\HOME.BAT
ECHO :: Returns to the Tagged Directory >> C:\BATCH\HOME.BAT
ECHO :: >> C:\BATCH\HOME.BAT
ECHO @ECHO OFF >> C:\BATCH\HOME.BAT
ECHO. >> C:\BATCH\HOME.BAT

C:\DOS\XSET CUR-DRIVE FDRIVE NUL
ECHO %CUR-DRIVE% >> C:\BATCH\HOME.BAT

C:\DOS\XSET CUR-DIR DIR
ECHO CD\%CUR-DIR% >> C:\BATCH\HOME.BAT

ECHO CLS >> C:\BATCH\HOME.BAT
ECHO C:\DOS\DIR >> C:\BATCH\HOME.BAT

CLS
ECHO.
ECHO  Ready to Return to
ECHO the Current Directory
ECHO.

:END
SET CUR-DRIVE=
SET CUR-DIR=

Explanation

    This works by first creating HOME.bat. If a previous version already exists, it is automatically overwritten. SAVE-DIR.bat begins that process by echoing some basic header text to HOME.bat. Next, the real work begins when XSET places the current drive letter into an environment variable called "CUR-DRIVE" and the current directory into one called "CUR-DIR". Each variable's value is then sent as a separate line to HOME.bat, with the directory value being preceded by a "CD\" command. To finish up HOME.bat, "Clear Screen" (CLS) and "Directory" (DIR) commands are sent to it.

    Next, SAVE-DIR.bat clears the current DOS screen and displays a prompt stating that DOS is ready to return to the current directory. Finally, the environment values are reset, thus removing them from memory.

    In operation, SAVE-DIR places the current drive letter on one line of HOME.bat. Then, a "Change Directory" (CD) command is placed on the next, followed by the current directory path & name. When Home.bat is run, it issues these basic commands:

(tagged drive)
CD\(tagged directory)
CLS
DIR

    Consequently, you are logged on to the tagged drive and taken to the tagged directory. HOME.bat finishes up by clearing the screen and showing a files listing of the returned-to directory. You may add the "DIR" switches you prefer to get say, an alphabetical list which pauses with each full screen, or whatever options you like. Here is the link to get XSET.


Usage

    This is the same as the previous example. Simply issue "SAVE-DIR" in any directory. A prompt appears saying DOS is ready to return to that directory. At any time when in DOS, enter "HOME" and you'll be taken back to the tagged directory. Again, this is better if you assign "SAVE-DIR and "HOME" to function keys.

    This last version is the one I actually use, although with some modifications and additions to suit my particular computer setup. I have SAVE-DIR programmed to F11, while F12 runs HOME.bat. I also use Loren Blaney's Color Directory as a replacement for the DOS "DIR" command. Thus, F12 takes me back to the tagged directory *and* displays that directory's contents in wide format with each file type in a different colour - all in one step.



 

SDEL.bat
(Improved)

    Here is an improvement on the SDEL.bat from Batch File Examples. It allows one to specify as many files as the command line will hold.


*    SDEL.bat (Improved)
Syntax: SDEL (File1, File2, File3...)
:: SDEL.bat (Improved)
:: Displays Files to Be Deleted
:: Prompts to Delete Files or Abort Operation
:: Allows as Many Files to be Specified as the Command Line can Hold
::
@ECHO OFF
CLS

IF "%1" == "" GOTO NO-FILES

ECHO. 
ECHO. 
ECHO    These Files Will Be Deleted:
ECHO. 
DIR | FIND "Directory"
ECHO. 
ECHO        %1 %2 %3 %4 %5 %6 %7 %9 %9
ECHO. 

ECHO.
ECHO  To Delete Listed Files, Press: D.
ECHO.
ECHO     To Cancel, Press: Escape.
ECHO.

CHOICE /C:D<- /N > NUL
IF ERRORLEVEL 2 GOTO END
IF ERRORLEVEL 1 GOTO AGAIN
GOTO END

:AGAIN
ECHO.
ECHO                    Deleting %1
DEL %1
SHIFT
IF NOT "%1" == "" GOTO AGAIN
GOTO END

:NO-FILES
ECHO.
ECHO            NO FILES GIVEN!
ECHO.

:END
C:\BATCH\DR.BAT

(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.)

Explanation

    This begins by checking to see if one or more file names were typed at the command line. Next it displays the directory name and shows up to the first nine files contained therein that are to be deleted. It then prompts the user to choose to delete the files or to abort the operation. If `D' is pressed, all files specified at the command line will be deleted one at a time with an on-screen message confirming this. As a final look, the directory is displayed to show the files are gone.


Usage

    This batch file should be run in the directory containing the files you wish to delete. It may be run from outside, but it means typing the path for each file. That tedium aside, the final line would give a directory listing of your current directory and not that in which the deletions have taken place.



 

THOUGHT.bat

    This will display a random "Thought of the Day" or any message you want seen upon bootup, as taken from a pool of messages.


*    THOUGHT.bat
:: THOUGHT.bat
:: Displays a Random "Thought of the Day" Message Upon Bootup
::
@ECHO OFF

CLS

C:\DOS\XSET NUMBER RANDOM 1 20

DIR C:\THOUGHTS\*.tht /B | XSET /LINE %NUMBER% FILE

MORE < C:\THOUGHTS\%FILE%

SET NUMBER=
SET FILE=
:END

Explanation

    This uses XSET, an update to the DOS "SET" command, to get a random number. Be sure XSET is in the C:\DOS directory. If not, change the path for it in the batch file.

    You will replace `20' with a number equal to the number of message files you will be creating. (See Usage, below.) DIR is then used to send a list of your message file names to XSET which selects one of the file names based on the random number it picked earlier. So if the number is `14', XSET will read the file name on Line 14. The chosen name is placed into an environmental variable called "FILE". That in turn, is used by the MORE command to display the file's contents on a cleared screen.


Usage

    You must first create a C:\THOUGHTS directory, or any other name and path you wish. Just be sure the batch file refers to whatever directory you have created. Then, simply make a number of text files with whatever message you wish. Give them a ".tht" extension and put them in the C:\THOUGHTS directory. To generate space around the message, have each file begin and end with some blank lines. Also, indent each message line a bit from both the left and right margins. Now, your message will stand out on the screen.

    Suggested messages might be proverbs, sayings, jokes, or new words. With the latter, place the word on the screen with its definition. If learned words keep appearing on the screen, replace them with new ones. Your vocabulary will increase with this idea.

    Another idea is to use this to learn to put names with images. These might be people, places or objects. Simply make up some .gif or .jpg images with names and place them into the THOUGHTS directory. Instead of using MORE to display a text file, use an image viewer to put one of your selected images on the screen after bootup.

    Place a line running THOUGHT.bat at the end of your AUTOEXEC.bat so that every time you boot, reboot, or run AUTOEXEC, a message will be displayed.

Here is the link to get XSET.



 

TOP.bat

    Have you ever wanted to change to another drive's root directory but had forgotten you had been working on that drive earlier? When you log on to it, you'll likely be in some sub directory. Here are two methods that will allow you to go immediately to the root directory of any drive on your system and see a files listing when you arrive. The first method below uses XSET, an update to the DOS "SET" command. It will be assumed it is in the "C:\DOS" directory. Afterward, a much simpler method to do the same thing will be shown.


*    TOP.bat
:: TOP.bat
:: Moves to and Displays the Root Directory of the Selected Drive
::
@ECHO OFF

IF "%1" == "" GOTO CURRENT

SET XSET=/UPPER
C:\DOS\XSET DRIVE=%1

IF "%DRIVE%" == "A" GOTO A-DRIVE
IF "%DRIVE%" == "B" GOTO B-DRIVE
IF "%DRIVE%" == "C" GOTO C-DRIVE
IF "%DRIVE%" == "D" GOTO D-DRIVE
IF "%DRIVE%" == "E" GOTO E-DRIVE
IF "%DRIVE%" == "F" GOTO F-DRIVE

:CURRENT
CD\
GOTO END

:A-DRIVE
A:
CD\
GOTO END

:B-DRIVE
B:
CD\
GOTO END

:C-DRIVE
C:
CD\
GOTO END

:D-DRIVE
D:
CD\
GOTO END

:E-DRIVE
E:
CD\
GOTO END

:F-DRIVE
F:
CD\

:END

CLS
CALL C:\BATCH\DR

SET XSET=
SET DRIVE=


Usage

    To use this batch file, simply enter "TOP" or "TOP (Drive Letter)". Be sure to place a space between the batch file name and the drive letter should you specify one. Do not include the drive letter colon ( : ). You'll then zoom to the root directory of the current or selected drive, with a list of its files and sub-directories shown on a cleared screen.


Explanation

    The first thing that happens is that the batch file checks to see if you entered a drive letter or not. If not, it branches to the "CURRENT" label where the "CD" (Change Directory) command switches to the root directory of the drive on which you currently are working. The file then branches to the end where "Clear Screen" and "DR" commands are issued. As always, you may substitute the DOS "DIR" command here in place of the "DR" one.

    Now, if you do specify a drive letter, including even one for the current drive, things get interesting. First the DOS "SET" command is used to set the XSET environment. In this instance, XSET is requested to make all variables be in upper case. So whether you issue a drive letter in lower or upper case on the command line, XSET will always make it be upper case. Thus, one of the succeeding "IF" statements will always be true (unless you type a drive letter that has not been included in the batch file's "IF" statements). One of the statements will be true because the batch file uses only upper-case letters with which to test.

    Without XSET, two tests for each drive letter would be required. One would have to be for a lower case possibility, and the other for an upper case one. By using XSET's "/UPPER" switch, any drive letter you issue at the command line will be converted to upper case, so double "IF" statements are unnecessary. (Note that newer versions of SET can be made to be case insensitive.)

    Next, XSET is used again to make an environment variable called "DRIVE" from the first parameter you type on the command line after the batch file's name. As just explained, if you type "top d" or "TOP D", the variable will be upper-case `D' in either instance. After that, this variable is checked to see if it matches one of the drive letters in the list. I have included drive letters from `A' to `F' inclusive. You may add or eliminate those which do, or do not, suit your setup.

    When the variable matches one of the drive letters, the batch file branches to a specific label that coincides with that drive letter. That letter is then issued in order to log you on to the appropriate drive, and as earlier, the "CD" command changes to the root directory of that drive. Afterwards, the batch file goes to the end. At that point, the root directory contents are displayed and any variables are removed from memory by setting them to equal nothing.
Here is the link to get XSET.


A Simpler Method

    It occurred to me after writing this that I was being a goof. I realised that I could do the same thing with just a few lines of code. Here is that version:


*    TOP.bat
:: TOP.bat (Simplified)
:: Moves to and Displays the Root Directory of the Selected Drive
::
@ECHO OFF

IF "%1" == "" GOTO CURRENT

%1:

:CURRENT
CD\
CLS
C:\BATCH\DR

    Yes... that's it! In this version, all that is required is to use "%1" in front of a colon. The drive letter will be filled in automatically. After that, the batch file issues "CD\" and displays a directory on a cleared screen. If no drive letter is given, the batch file immediately issues "CD\" and does the directory display.



 

UPDATE A DIRECTORY

    So you like to keep a backup directory of your latest files but never seem to be able to keep it current. Here is a way to be sure that backup directory will contain all the source files and only their latest versions. Afterwards, another batch file will be presented that updates both the source and destination directories so that both will contain exactly the same files and only the latest versions. Finally, a third version demonstrates a different method.


*    UPDATE.bat
:: UPDATE.bat
:: Updates the Chosen Directory with the Latest Files
::
@ECHO OFF

REPLACE %1\*.* %2 /A
REPLACE %1\*.* %2 /U

:END
                                 ________


Explanation

    This simple batch file uses REPLACE to add files from the source that do not exist in the destination (second) directory via "/A". The second line overwrites files in the destination directory with those from the source directory only if the source files are newer. That is done by the "/U" (Update) switch. You specify both the source and destination directories via "%1" and "%2". Thus it may be used to backup any directory to any other directory even on another drive.


Usage

    Simply enter "REPLACE (source directory) (target directory)". You may specify any directories on any drives provided they already exist. Files in the first directory specified will be added to the second specified directory, or be updated if they already exist in that second directory. So if the destination of the files is D:\BACKUP, you would enter "UPDATE D:\BACKUP".



An Improvement

    Here's one step beyond the above. It will synchronise two directories by placing the same files from each directory into the other, and by being sure that they are the latest ones.


*    UPDATE.bat
:: UPDATE.bat (Improved)
:: Updates both the Source and Destination Directories
::  with the Latest Files
::
@ECHO OFF

REPLACE %1\*.* %2 /A
REPLACE %1\*.* %2 /U

REPLACE %2\*.* %1 /A
REPLACE %2\*.* %1 /U

:END
                                 ________


Explanation

    This works as before with the first lines adding and updating files from the first directory to the second. Then it repeats the process from the second to the first. So if there are three files in the first directory and only two in the second, the extra file will be added to the second directory. Also, if the first directory's files are newer, they will be copied to the second directory and overwrite the older versions in that directory.

    Next, if there are any files in the second directory that are not in the first, they will be added to the first. Also, any files not overwritten in the second directory by first operation, means that the second directory's files must be the same or newer. If they are newer, they will be used to overwrite their older versions in the first directory. Thus, when the batch file finishes, both directories will contain the same files, and those files will only be the latest versions.



A Variation

    Here's a different way to do just the single update. It uses a newer version of DOS' "XCOPY" command called "XXCOPY". This batch file will allow one to have a working directory and with the latest files kept in the backup directory. It also allows one to work in the destination (BACKUP) directory but have the latest files kept only in that BACKUP directory. This is without fear of overwriting by those in the work directory - unless the work directory files are newer.


*    UPDATE.bat
:: UPDATE.bat (XXCOPY Version)
:: Updates both the Source and Destination Directories
::  with the Latest Files
:: Updates the Chosen Directory with the Latest Files
:: Deletes Copied Files from the Source
::
@ECHO OFF

XXCOPY C:\WORK\*.* C:\BACKUP /BN /RC /ED /YY > NUL

:END
                                 ________


Explanation

    XXCOPY will copy all files from the WORK directory to the BACKUP if they are newer or if they do not exist in the BACKUP directory by using its "/BN" (Backup New) switch. Then, via "/RC" (Remove-after-Copy), it removes from the source only those files that were copied. Any files remaining there must be older, and thus must have been updated sometime previously right in the BACKUP directory. You may then delete the files remaining in the WORK directory because they are older. The "/ED" switch preserves any directories that become empty, while "/YY" and "> NUL" eliminate any prompts and messages.


Usage

    Enter "Update". No source & destination directories are needed because this batch file is dedicated to the WORK and BACKUP directories. Of course, if you use other directory pairs, you may substitute `%1' and `%2' as was done previously, and then specify the desired directories at the command line.

    XXCOPY may be obtained from -XXCOPY.com.



More of these are in
Advanced Batch Files II.




Batch Tutorial Obtain 500+ Batch Files Batch Examples
Advanced Batch II Advanced Batch III Batch Tips



Main DOS Page