Search This Blog

Loading...
StumbleUpon

Batch Files Tutorial , Example , And More......




Batch Files
What are batch files? Batch files are not programs, pre se, they are lists of command line instructions
that are batched together in one file. For the most part, you could manually type in the lines of a batch
file and get the same results, but batch files make this work easy. Batch files do not contain "compiled" code
like C++ so they can be opened, copied and edited. They are usually used for simple routines and low-level machine
instruction, but they can be very powerful. If you look in your
.SYS, .CFG, .INF and other types. These are all kinds of batch
files. This may shock you, but while most applications are writen in Basic or
C++ they sit on a mountain of batch files. Batch files are the backbone of the
Windows operating system, delete them and you've effectively disabled the OS.
There is a reason for this. The system batch files on each computer are unique the
that computer and change each time a program is loaded. The operating system
must have access to these files and be able to add and delete instructions from them.



Creating Batch files
Simple instructions
Open a text editor like notepad(NOT word or wordpad)
Type or copy this text: @ECHO OFF
ECHO.
ECHO This is a batch file
ECHO.
PAUSE
CLS
EXIT

Save this as batchfile.bat, make sure there is no .txt extension after the .bat
Double-click the file icon
This is a little batch file I wrote that I use every day. It deletes the cookies that get dumped to my hard drive every time I go online. I could set my browser preferences not to accept cookies, but sometimes cookies are useful. Some CGI pages are unusable with cookies, sometimes when you enter a password for a Website, the site uses a cookie to remember your password. I just do not need hundreds of cookie files taking up space after I close my browser. With this batch file, all I have to do is double-click it and it deletes my cookies. Feel free to cut and paste this code to your Notepad or Wordpad. Save it as cookiekill.bat on your Desktop.


cls
REM *******************************************
REM **Cookie Kill Program Will not work in NT**
REM *******************************************

deltree /y c:\windows\cookies\*.*
deltree /y c:\windows\tempor~1\*.*
pause
cls
REM Cookies deleted!



What does the batch file do? The first line has the command cls. cls clears the screen window of any previous data. The next three lines start with REM for "remark." Lines begining with REM do not contain commands, but instructions or messages that will be displayed for the user. The next two lines begin with the command deltree, deltree not only deletes files but directories and sub-directories. In this case the file is deleting the directory cookies and all the files inside. This directory is automatically rebuilt. The deltree has been passed the parameter /y, this informs the process to answer "YES" to any confirmation questions. Sometimes you type the DEL or one of its cousins, the system will ask "Are sure you want to do this?" setting /y answers these prompts without interupting the process. The pause command halts the process temporarily and shows the users a list of all the files being deleted. cls clears the screen again, another REM line tells the user that the files are deleted. The last line contains only :end and returns the process to the command prompt. This version was created to show the user everything that is taking place in the process. The version bellow does the same thing without showing the user any details.

cls
@echo off

deltree /y c:\windows\cookies\*.*
deltree /y c:\windows\tempor~1\*.*

cls


Without REM lines there are no comments. The @echo off command keeps the process from being "echoed" in the DOS window, and without the pause and :end lines, the process runs and exits without prompting the user. In a process this small it is okay to have it be invisible to the user. With more a complex process, more visual feedback is needed. In computing there is fine line between too much and too little information. When in doubt give the user the oportunity to see what is going on.

This version is a little more thurough, deletes alot of junk cls
@ECHO OFF
ECHO. ***********************************
ECHO. ** Clean Cookies and Temp Files **
ECHO. ** Will not work in NT **
ECHO. *******************************
deltree /y c:\windows\cookies\*.*
deltree /y c:\windows\tempor~1\*.*
deltree /y c:\progra~1\Netscape\Users\default\Cache\*.jpg
deltree /y c:\progra~1\Netscape\Users\default\Cache\*.gif
deltree /y c:\progra~1\Netscape\Users\default\Cache\*.htm
deltree /y c:\progra~1\Netscape\Users\default\archive\*.htm
deltree /y c:\progra~1\Netscape\Users\default\archive\*.gif
deltree /y c:\progra~1\Netscape\Users\default\archive\*.jpg
deltree /y c:\windows\temp\*.*
deltree /y c:\temp\*.*
deltree /y c:\windows\Recent\*.*
deltree /y c:\recycled\*.*
cls
EXIT


"C:\windows\history\today" will rebuld itself if you delete it. It's not a file, it's a specially configured directory structure that DOS doesn't see the same way that windows does. C:\windows\history\today doesn't actually exist as DOS sees it. Go into the C:\windows\history directory and type DIR/A this will show you the hidden directories and how they are named.

WINNT Version @ECHO OFF
ECHO **************************************************
ECHO ** DEL replaces DELTREE, /Q replaces /Y **
ECHO **************************************************

del /Q c:\docume~1\alluse~1\Cookies\*.*
REM Change alluse~1 in the above line to your userID
del /q c:\winnt\temp\*.*
del /q c:\temp\*.*
del /q c:\winnt\Recent\*.*
del /q c:\*.chk
EXIT

Add these lines for XP - Provided by Patrick R. del /q C:\Windows\Temp\Adware\*.*
del /q C:\Windows\Temp\History\*.*
del /q C:\Windows\Temp\Tempor~1\*.*
del /q C:\Windows\Temp\Cookies\*.*



One thing I do quite often is erase old floppy disks. I might have a stack of them and I don't care what's on them, but I want all the files gone including potential virii(everyone says "viruses" but "virii" is the proper term. Snob!). But I get tired of opening a DOS prompt and typing in the command to format the disk. So I wrote a one line batch file that does it for me. Save it as: "disk_wipe.bat"

format a: /u
Put a disk in the drive and double-click the .bat file icon.




Batch File Utilities and Commands
Any valid DOS command may be placed in a batch file, these commands are for setting-up the structure and flow of a batch file.

CLS
Clears the screen


--------------------------------------------------------------------------------


EXIT
Exits the command-line process when the batch file terminates
EXIT

--------------------------------------------------------------------------------


BREAK
When turned on, batch file will stop if the user presses <>-<> when turned off, the script will continue until done.
BREAK=ON

BREAK=OFF

--------------------------------------------------------------------------------


CALL
Calls another batch file and then returns control to the first when done.
CALL C:\WINDOWS\NEW_BATCHFILE.BAT

Call another program
CALL C:\calc.exe
Details.
--------------------------------------------------------------------------------


CHOICE
Allows user input. Default is Y or N.
You may make your own choice with the /C: switch. This batch file displays a menu of three options. Entering 1, 2 or 3 will display a different row of symbols. Take note that the IF ERRORLEVEL statements must be listed in the reverse order of the selection. CHOICE is not recognized in some versions of NT. @ECHO OFF
ECHO 1 - Stars
ECHO 2 - Dollar Signs
ECHO 3 - Crosses


CHOICE /C:123

IF errorlevel 3 goto CRS
IF errorlevel 2 goto DLR
IF errorlevel 1 goto STR

:STR
ECHO *******************
ECHO.
PAUSE
CLS
EXIT

:DLR
ECHO $$$$$$$$$$$$$$$$$$$$
ECHO.
PAUSE
CLS
EXIT

:CRS
ECHO +++++++++++++++++++++
ECHO.
PAUSE
CLS
EXIT



--------------------------------------------------------------------------------


FOR...IN...DO
Runs a specified command for each file in a set of files. FOR %%dosvar IN (set of items) DO command or command strcuture.
%%dosvar is the variable that will hold items in the list, usually a single leter: %%a or %%b. Case sensitive, %%a is different from %A. The items in the (set) are assigned to this variable each time the loop runs.

(set of items) is one item or multiple items seperated by commas that determine how many times the loop runs.

command or command strcuture is the operation you want to perform for each item in the list.

This code will run through the set (A, B, C), when it gets to B it will print the message: "B is in the set!"
FOR %%b in (A, B, C) DO IF %%b == B echo B is in the set!

This line will print the contents of C:\windows\desktop
FOR %%c in (C:\windows\desktop\*.*) DO echo %%c

So, you may create your own list or use various objects like files to determine the loop run.
Details.
--------------------------------------------------------------------------------


GOTO
To go to a different section in a batch file. You may create different sections by preceding the name with a colon. :SUBSECTION
Programmers may find this similar to funtions or sub-routines.

@ECHO OFF
:FIRSTSECTION
ECHO This is the first section
PAUSE
GOTO SUBSECTION

:SUBSECTION
ECHO This is the subsection
PAUSE



Skip sections of a batch file
@ECHO OFF
:ONE
ECHO This is ONE, we'll skip TWO
PAUSE
GOTO THREE

:TWO
ECHO This is not printed

:THREE
ECHO We skipped TWO!
PAUSE
GOTO END
:END
CLS
EXIT



Looping with GOTO
:BEGIN
REM Endless loop, Help!!
GOTO BEGIN

Use with CHOICE
--------------------------------------------------------------------------------


IF, IF EXIST, IF NOT EXIST
IF EXIST C:\tempfile.txt
DEL C:\tempfile.txt
IF NOT EXIST C:\tempfile.txt
COPY C:\WINDOWS\tempfile.txt C:\tempfile.txt

Use with "errorlevel"
The generic paramater errorlevel refers to the output another program or command and is also used with the CHOICE structure. If you try and run a command in a batch file and produces an error, you can use errorlevel to accept the returned code and take some action. For example, let's say you have a batch file that deletes some file. COPY C:\file.txt C:\file2.txt

If "file.txt" doesn't exist, you will get the error: COULD NOT FIND C:\FILE.TXT. Instead, use a structure like this to create the file, then copy it by accepting the error.
@ECHO OFF
:START
COPY file.txt file2.txt
IF errorlevel 1 GOTO MKFILE
GOTO :END

:MKFILE
ECHO file text>file.txt
GOTO START

:END
ECHO Quitting
PAUSE

an errorlevel of 1 means there was an error, errorlevel of 0 means there was no error. You can see these levels by adding this line after any line of commands: ECHO errorlevel: %errorlevel%
Details.
--------------------------------------------------------------------------------


PAUSE
Pauses until the user hits a key.

This displays the familiar "Press any key to continue..." message.

--------------------------------------------------------------------------------


REM
Allows a remark to be inserted in the batch script.

REM DIR C:\WINDOWS Not run as a command
DIR C:\WINDOWS Run as a command

--------------------------------------------------------------------------------


ECHO
Setting ECHO "on" will display the batch process to the screen, setting it to "off" will hide the batch process.
@ECHO OFF Commands are NOT displayed
@ECHO ON Commands are displayed

ECHO can also be used in batch file to send output to the screen: @ECHO OFF
ECHO.
ECHO Hi, this is a batch file
ECHO.
PAUSE

ECHO. sends a blank line.

To echo special characters, precede them with a caret:

ECHO ^<>
Otherwise you will get an error.

The @ before ECHO OFF suppresses the display of the initial ECHO OFF command. Without the @ at the beginning of a batch file the results of the ECHO OFF command will be displayed. The @ can be placed before any DOS command to suppress the display.

Breaking long lines of code
You may break up long lines of code with the caret ^. Put it at the end of a line, the next line must have space at the begining. Example: copy file.txt file2.txt
would be: copy file.txt^
file2.txt

--------------------------------------------------------------------------------


SET
Use to view or modify environment variables. More.
--------------------------------------------------------------------------------


LASTDRIVE
Sets the last drive in the system.
lastdrive=Q

--------------------------------------------------------------------------------


MSCDEX
Loads the CD-ROM software extensions(drivers), usually so an operating system can be then loaded from CD. See the AUTOEXEC.BAT section for special instructions concerning CD ROM installation. Installing windows from a CD when the CDROM is not yet configured





--------------------------------------------------------------------------------

The AUTOEXEC.BAT file
AUTOEXEC.BAT stands for automatic execution batch file, as in start-up automatically when the computer is turned on. Once a very important part of the operating system, it is being less used and is slowly disapearing from Windows. It is still powerful and useful. In NT versions it is called AUTOEXEC.NT, click here for more information.

Before the graphical user interface(GUI, "gooey") of Windows, turning on a PC would display an enegmatic C:\> and not much else. Most computer users used the same programs over-and-over, or only one program at all. DOS had a batch file which set certain system environments on boot-up. Because this was a batch file, it was possible to edit it and add a line to start-up the user's programs automatically.

When the first version of Windows was released users would turn their PCs on, and then type: WIN or WINDOWS at the prompt invoking the Windows interface. The next version of Windows added a line to the AUTOEXEC to start Windows right away. Exiting from Windows, brought one to the DOS prompt. This automatic invocation of Windows made a lot of people mad. Anyone who knew how to edit batch files would remove that line from the AUTOEXEC to keep Windows from controling the Computer. Most users do not even know that DOS is there now and have never seen it as Windows hides the any scrolling DOS script with their fluffy-cloud screen. At work I will often have to troubleshoot a PC by openning a DOS shell, the user's often panic, believing that I have broken their machine because the screen "turns black".

Most current versions of Windows have a folder called "Start-up." Any program or shortcut to a program placed in this folder will start automatically when the computer is turned on. This is much easier for most users to handle than editing batch files.

Old versions of DOS had a AUTOEXEC that looked like this:

@echo off
prompt $p$g


All this really did way set the DOS prompt to ">"

Later versions looked like this:
cls
@echo off
path c:\dos;c:\windows
set temp=c:\temp
Lh mouse
Lh doskey
Lh mode LPT1 retry

This AUTOEXEC.BAT loads DOS & then Windows. Sets up a "temp" directory. Loads the mouse driver, sets DOSKEY as the default and sets the printer retry mode. "Lh" stands for Load High, as in high memory.

An AUTOEXEC.BAT from a Windows 3.11 Machine
@ECHO On
rem C:\WINDOWS\SMARTDRV.EXE
C:\WINDOWS\SMARTDRV.EXE 2038 512
PROMPT $p$g
PATH C:\DOS;C:\WINDOWS;C:\LWORKS;C:\EXPLORER.4LC
SET TEMP=C:\DOS
MODE LPT1:,,P >nul
C:\DOS\SHARE.EXE /F:150 /L:1500
C:\WINDOWS\mouse.COM /Y
cd windows
WIN




This version simply sets DOS to boot to Windows.

SET HOMEDRIVE=C:
SET HOMEPATH=\WINDOWS



Whenever a program is installed on a computer, the setup program or wizard will often edit the AUTOEXEC. Many developer studios will have to "set a path" so programs can be compiled or run from any folder. This AUTOEXEC is an example of that: SET PATH=C:\FSC\PCOBOL32;C:\SPRY\BIN
SET PATH=C:\Cafe\BIN;C:\Cafe\JAVA\BIN;%PATH%
SET HOMEDRIVE=C:
SET HOMEPATH=\WINDOWS



This AUTOEXEC sets the path for COBOL and JAVA development BINs. This way, the computer knows where to look for associated files for COBOL and JAVA files if they are not located directly in a BIN folder.





Sets all the devices and boots to Windows.
When the "REM" tags are removed the device commands become visible.
@SET PATH=C:C:\PROGRA~1\MICROS~1\OFFICE;%PATH%
REM [Header]
@ECHO ON
REM [CD-ROM Drive]
REM MSCDEX.EXE /D:OEMCD001 /L:Z
REM [Display]
REM MODE CON: COLS=80 LINES=25
REM [Sound, MIDI, or Video Capture Card]
REM SOUNDTST.COM
REM [Mouse]
REM MOUSE.COM
REM [Miscellaneous]
REM FACTORY.COM


For loading Windows from a CD @echo off
MSCDEX.EXE /D:OEMCD001 /L:D
d:
cd \win95
oemsetup /k "a:\drvcopy.inf"

For loading CDROM drivers
Removing the "REM" tags uncomments the commands and runs them.
REM MSCDEX.EXE /D:OEMCD001 /l:d
REM MOUSE.EXE


AUTOEXEC in NT
NT does not use AUTOEXEC.BAT, the file is called AUTOEXEC.NT and should be found in the C:\WINNT\system32 folder. Here is a sample AUTOEXEC.NT file:
@echo off

REM AUTOEXEC.BAT is not used to initialize the MS-DOS environment.
REM AUTOEXEC.NT is used to initialize the MS-DOS environment unless a
REM different startup file is specified in an application's PIF.

REM Install CD ROM extensions
lh %SystemRoot%\system32\mscdexnt.exe

REM Install network redirector (load before dosx.exe)
lh %SystemRoot%\system32\redir

REM Install DPMI support
lh %SystemRoot%\system32\dosx
SET PCSA=C:\PW32
dnp16.exe


*.NT and *.CMD
.NT and .CMD may be used as .BAT files were used in earlier versions of Windows. You may notice on NT systems that there are fewer and fewer .BAT files. Try seaching for .NT or .CMD and you will find many of the same types of batch files that were available as .BATs. For example: CONFIG.NT has a similar function to the old CONFIG.SYS of Windows.
--------------------------------------------------------------------------------

CONFIG.SYS
In Windows systems config.sys is used to set the initial values of the environment variables. To see your current settings, type SET on a command line. In early versions config.sys is a text file you can edit. In later versions it is a complied file that cannot be changed in a text editor. In newer NT versions it is not used at all. Try msconfig.exe instead. REM [Header]
FILES=20
BUFFERS=20
DOS=HIGH,UMB
REM [SCSI Controllers]
REM DEVICE=SCSI.SYS
REM [CD-ROM Drive]
REM DEVICE=CDROM.SYS /D:OEMCD001
REM [Display]
REM DEVICE=DISPLAY.SYS
REM [Sound, MIDI, or Video Capture Card]
REM DEVICE=SOUND.SYS
REM [Mouse]
REM DEVICE=MOUSE.SYS
REM ------------------
REM [Miscellaneous]
REM DEVICE=SMARTDRV.EXE




--------------------------------------------------------------------------------

Types of "batch" files in windows
INI, *.ini - Initalization file. These set the default variables for the system and programs. More

CFG, *.cfg - Configuration files.

SYS, *.sys - System files, can sometimes be edited, mostly compiled machine code in new versions. More.

COM, *.com - Command files. These are the executable files for all the DOS commands. In early versions there was a seperate file for each command. Now, most are inside COMMAND.COM.

NT, *.nt - Batch files used by NT operating systems. More.

CDM, *.cmd - Batch files used in NT operating systems. More.

Answer Files and Unattended Installations
Customizing Unattended Installations
Answer Files
Customizing and Automating Installations
Automate Windows Installations

--------------------------------------------------------------------------------

Batch File Parameters
You may put and use command-line parameters into your batch-files.

Suppose you had a batchfile called "test.bat" and these were the contents:
@echo off
if (%1) == (Hi) echo %1

and at the command line you entered: test.bat Hi, the output would be "Hi". If you entered test.bat bye you would get no response because the parameter did not match. the "%1" refers to the first parameter on the command line after the batch file name. If you want to two parameters, the script would look like this:
@echo off
if (%1) == (Hi) echo %1 %2

You could also just spit out what someone types in without a condition:

@echo off
echo %1 %2 %3 %4 %5 %6

Then typing test.bat dont tell me what to do would produce
dont tell me what to do because it is set up to handle 6 parameters and there are six words. You can tease someone by changing the order:
@echo off
echo %6 %3 %1 %2 %5 %4

do me dont tell to what

Making your own variables
You may use the SET command to create your own internal paramaters. This batch file:
@echo off
set myvar=Hi Joe
echo %myvar% is myvar

Will print Hi Joe is myvar. Notice a few important points. when we initialize myvar there are no % around it. When we use it, it must be between two %. Also, there must be no spaces between the = and the terms. When myvar is not in a set command or between % it is treated as a literal string.

You can make up your own parameter names and have many of them:
@echo off
set name=John Smith
set address=1 main street
set city=helltown

echo %name%
echo %address%
echo %city%

You could also assign command line parameters to the variables:
@echo off

set name=%1
set address=%2
set city=%3

echo %name%
echo %address%
echo %city%

The command line usually sees the space as a parameter delimiter, use double quotes " to make it ingore the spaces: test.bat "Joe Smith" "1 Main Street" "Helltown".
Something important to remember about SET, it actaully creates a variable name in the file So if you enter SET NAME=Joe on the command line or in a batch file and then go to the command line and enter ECHO %NAME% the response will be Joe. Entering SET with no parameters will also show the whole list of SET variables. These will be erased when you reboot.
--------------------------------------------------------------------------------

The power of command line switches
Most GUI programs have some kind of command line support which means you may automate their operation through batch files. For example, DOS does not have a built-in email sending function like UNIX. However, using an installed email program like Outlook, you may "force feed" the program on the command line. Outlook examples:outlook /c ipm.note will open a blank email, outlook /c ipm.note /m msmith@yahoo.com will open a blank email with the indicated address, outlook /c ipm.note /a myfile.doc attaches a file. More outlook switches, outlook programming.

An example using command line with winzip.
--------------------------------------------------------------------------------


The Windows Installation Catch-22
You have a new computer with a unformated hard drive, or a drive with only DOS loaded. You want to load Windows from a CD, but you can't see the CD ROM from the DOS prompt. This is messy and can be screwed-up easily, luckily mistakes on this don't cause permanent damage. If you're lucky the CD ROM you have came with an installation disk(on floppy, of course). Putting this disk in and running the INSTALL.EXE or SETUP.EXE will install the drivers for you and alter the system files so you can load Windows from the CD ROM(Linux, by the way, has no problem with this!). If there is no INSTALL.EXE on the disk, you will have to edit lines in two files on your Windows 95 Boot/Install floppy disk. These files are: CONFIG.SYS and AUTOEXEC.BAT. Open these files for editing are look for lines that look like these:

REM DEVICE=CDROM.SYS /D:OEMCD001

And
REM C:\DOS\MSCDEX.EXE /D:OEMCD001

They may or may not be REMed out. You will need to change the "/D:OEMCD001" part of these lines to reflect the CD ROM that you have. For example if you have a Memorex it might be "/D:MSCD001". But be sure, check any manuals you might have lying around. If not, go to the manufacturer's website and down load the installation files. You will also need to figure out which drive letter it will be. If you only have on hard disk, it will be "D:" as in "/D:MSCD001," if you have two hard drives, or your drive is in several partitions, it might be "E:" or "F:". So then the line would be "/E:MSCD001" or "/F:MSCD001"

The Final line in CONFIG.SYS might be like this: DEVICE=C:\WINDOWS\SBIDE.SYS /D:MSCD001 /V /P:170,15



=====================================================================================================================================



PRELIMINARY
Here are example batch files. They will not be explained line by line, except for the more ambiguous ones. The title remarks should suffice so you'll understand their operation, although some will be preceded by a syntax example. Explanatory notes to the right are not part of the file. Do not type them in. For further explanation, see Batch File Basics, before reading this section.

The "DR" command is a batch file that runs an after-market directory program I use called Color Directory. It is used with the batch files here to confirm that an operation has happened. You may substitute DOS' "DIR" or "XDIR" command with its switches set to your preferences, or use any directory display program of your choosing.

Note that full paths to commands used in these batch files have not always been shown. This is to reduce confusion for batch-file newbies. To be fully efficient, any program called or run from a batch file should be preceded by its full path.

Be aware that Doctor DOS will not be responsible for any problems encountered through 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

CDD.bat

("Change/Display Directory" Bat)
Syntax: CDD (Directory Name)

:: CDD.bat
::
:: Changes to a Specified Directory
:: Displays a File and Subdirectory List
::
@ECHO OFF

CD %1 "%1" Represents the Directory Name.
You Type at the Command Line.
ECHO. Adds a Blank Line to the Display.
C:\BATCH\DR
________


CLU.bat

("Clear Screen - Move Up" Bat)


:: CLU.bat
::
:: Moves Up One Directory Level
:: Displays Directory on a Cleared Screen.
::
@ECHO OFF

CD..
CLS
ECHO. Adds a Blank Line to the Display.
C:\BATCH\DR
________



CFB.bat

("Copy From `B'" Bat)
Syntax: CFB (Optional File name)

:: CFB.bat
::
:: Copies All or Specified Files From the
:: B Drive Root to the Current Directory
:: (A Sub-Directory Location May be Specified)
:: (Hidden Files are Excepted.)
::
@ECHO OFF
ECHO. Leaves a blank line for separation.

IF "%1" == "" XCOPY B:\*.* If there is no file name, all
IF NOT "%1" == "" XCOPY B:\%1 files in the B drive root will
ECHO. be copied.
C:\BATCH\DR If there is a file name, only
it will be copied.
________



CTB.bat

("Copy to `B'" Bat)
(Substitute a USB flash-drive
letter to copy to it.)

Syntax: CTB (Optional File Name)

:: CTB.bat
::
:: Copies All or Specified Files to a B-Drive Floppy
:: (Hidden Files are Excepted.)
::
@ECHO OFF

ECHO. Adds a Blank Line to the Display.
IF "%1" == "" XCOPY *.* B:\ If there is no file name, all files
IF NOT "%1" == "" XCOPY %1 B:\ in the current directory will be
C:\BATCH\DR B:\ copied.
If there is a file name, only
it will be copied.


________



DAF.bat

("Delete All Files" Bat)


:: DAF.bat
::
:: Deletes All files in the Current Directory
:: With Prompts and Warnings
::
:: (Hidden, System, and Read-Only Files are Not Affected)
::
@ECHO OFF

DEL . `.' Represents the Current Directory.
DR



DAF.bat
(Variation)

("Delete All Files" Bat)

:: DAF.bat (Variation)
::
:: Deletes All files in the Current Directory
:: Skips "Are You Sure?" and Other Messages
:: (Hidden, System, and Read-Only Files are Not Affected)
::
@ECHO OFF

ECHO Y | DEL . > NUL Echoes (sends) a "Yes" Answer to
the "Delete" Prompt and Hides
Other Messages.
ECHO. Adds a Blank Line to the Display.
C:\BATCH\DR


________



DELE.bat

("Delete Except" Bat)
Syntax: DELE (File name) to Not be deleted)

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

MD SAVE Makes a Temporary "SAVE" Directory.
XCOPY %1 SAVE > NUL "> NUL" Suppresses On-Screen Messages.
ECHO Y | DEL . > NUL Deletes all Files in the Current
Directory showing no Prompts.

MOVE SAVE\*.* . > NUL Returns Excepted File(s) to the
RD SAVE Current Directory.
Removes "SAVE" Directory.
ECHO. Adds a Blank Line to the Display.
C:\BATCH\DR Displays the Results of the Operation.


To see a variation of this batch file which will allow multiple files of differing names to be excepted, go to Advanced Batch Files.


--------------------------------------------------------------------------------

DELT.bat

("Delete Tree" Bat)
(Requires DOS 6 or Newer)

Syntax: DELT (Directory Name)

:: DELT.bat
::
:: Deletes Specified Directory and All Files
:: and Directories Below
:: Prompts "Are You Sure?" Before Deletion Commences.
::
@ECHO OFF

IF "%1" == "" GOTO NO-DIRECTORY Prompts if No Directory was Specified

ECHO. Displays a Blank Line.
ECHO. Displays a Blank Line.

TREE %1 Displays the Directory Structure
to be Deleted.
DELTREE %1 Deletes Directory Structure.
DR
GOTO END Directs DOS to End the Batch File
Operation.

:NO-DIRECTORY
ECHO.
ECHO No Directory Specified
ECHO.

:END
________



MCD.bat

("Make/Change Directory)
Syntax: MCD (File Name)

:: MCD.bat
:: Makes and Changes to the Specified Directory
::
@ECHO OFF

CLS
MD %1
CD %1
________



MDEL.bat

("Multiple Delete" Bat)
Syntax: MDEL (File Name File Name File Name, etc.)

:: MDEL.bat
:: Allows Deletion of Up to Nine Files
:: with Different Names and Extensions
:: Wildcards are Permitted
::
@ECHO OFF

CLS Clears the Screen.
FOR %%F IN (%1 %2 %3 %4 %5 %6 %7 %8 %9) DO DEL %%F See Text.

ECHO. Adds a Blank Line to the Display.
C:\BATCH\DR Confirms the Operation.

This uses the DOS "FOR-IN-DO" (FOR) command and replaceable parameters. Basically, it means "FOR each Item INside the Brackets, DO the given command". In this case, it will take each file name you give at the command line and substitute it for one of the percent-numbers. These percent-numbers are replaceable parameters, with "%1" representing the first file name, "%2, the second, and so on. Wild card characters, ` ? ' and ` * ', may be used in file names.

The batch file deletes each item inside the brackets, which will be those file names you typed at the command line. Each file name is substituted for one of the percent numbers. You may specify up to nine file names or groups.


MDEL.bat (Improved)

("More Powerful "Multiple Delete"" Bat)
Syntax: MDEL (File Name File Name File Name, etc.)

:: MDEL.bat (Improved)
:: Allows Deletion of Multiple Files
:: with Different Names and Extensions
@ECHO OFF

CLS Clears the Screen.

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

ECHO. Adds a Blank Line to the Display.
C:\BATCH\DR Confirms the Operation.

This version allows one to type as many file names as the command line can hold. It uses the "SHIFT" command. That allows each file name on the command line to shift down one number to become the first replaceable parameter. Thus, the second file name will become "%1" after the SHIFT command is issued, the third file name becomes "%2", and so on. After yet another SHIFT command, the third file name will be in position "one" (%1). As long as there are file names left on the command line, they will be shifted one at a time into position number `1'. Then, each is deleted in turn with an on-screen message to that effect being displayed.

Finally, when no file names are left, the "IF NOT" statement becomes false because "%1" will then be equal to nothing. Thus the batch file does not loop to "AGAIN" and instead goes on to display the directory listing confirming the files are gone.

________



MU.bat

("Move Up" Bat)
Syntax: MU (File Name File Name File Name, etc.)

:: MU.bat (Move Up)
:: Move All or Specified Files Up One Level
::
@ECHO OFF

If "%1" == "" GOTO MOVE-ALL
If NOT "%1" == "" GOTO MOVE-SPEC

:MOVE-ALL
MOVE /-Y *.* ..
GOTO END

:MOVE-SPEC
FOR %%F IN (%1 %2 %3 %4 %5 %6 %7 %8 %9) DO MOVE /-Y %%F ..

:END
ECHO. Adds a Blank Line to the Display.
F:\BATCH\DR
________


This allows one to move up to nine files or file groups into the parent directory one level up. I use it because I have many directories in which there is a WORK subdirectory. After doing my work, I want to move the completed files into the parent directory and use this batch file to do so. The "/-Y" will prompt you if any files in the parent directory are about to be overwritten. You may choose to overwrite or not. The batch file will then resume and go on to the next file. (Be aware, some DOS versions do not recognise this switch and will overwrite without prompting.)

You may modify this batch file into CU.bat (Copy Up) by replacing the MOVE commands with:

COPY *.* .. /-Y

or

COPY %%F .. /-Y .

Note that the "Overwrite" switch comes at the end of the line when COPY is used.

________



SDEL.bat

("Safe Delete" Bat)
Syntax: SDEL (File name)

:: SDEL.bat (Safe Delete)
:: Displays File to Be Deleted
:: Prompts to Delete File or Abort Operation
:: Wildcards May be Used to Delete File Groups
::
@ECHO OFF
CLS

IF NOT "%1" == "" GOTO DISPLAY

ECHO.
IF "%1" == "" ECHO No File(s) Specified! Prompts if No File
ECHO. is Given.
GOTO END

:DISPLAY
ECHO %0 %1 Gives the Batch File Name
ECHO. and File to be Deleted.
ECHO These Files Will Be Deleted:
ECHO.
DIR %1 | FIND "Directory" Displays the Path and
DIR %1 /B /P Files to be Deleted.

ECHO.
ECHO To Delete Listed Files, Allows the User to
ECHO Press Any Key Continue or Abort.
ECHO.
ECHO To Cancel, Press: `Control-C'
ECHO.

PAUSE > NUL

:DELETE Deletes Selected File(s).
DEL %1
ECHO.

:END
ECHO. Adds a Blank Line to the Display.
C:\BATCH\DR Confirms the Operation.


An improved SDEL.bat may be found in Advanced Batch Files.

________



STEP.bat

("Step" Bat)
(Requires MS-DOS 6.2 or Newer)
Syntax: STEP (Batch File Name with No Extension, Parameters)

:: STEP.bat
:: Allows one to Step through a Batch File
:: To Test Each Line
::
@ECHO OFF
COMMAND /Y /C %1.bat %2 %3 %4
:END
________


This simple example allows one to run a batch file a line at a time to test it. It runs another copy of DOS' COMMAND.com. The "/Y" switch is what does the stepping. It displays each line and asks if you wish to run it or not by pressing "Y" or "N". You may exit this procedure at any time by pressing "CONTROL-C". Also, by pressing "Escape", the batch file will continue on its own from the current line.

The "/C" switch runs the specified command and then returns to the base COMMAND.com - either after the stepping procedure finishes, or after pressing "CONTROL-C".

When running this batch file, don't type the ".bat" extension. STEP.bat does that for you via the "%1.bat" replaceable parameter. If the batch file requires additional parameters, you may specify up to three via the " %2 %3 %4" replaceable parameters. Here's a syntax example:

STEP SDEL TEST.txt

This will step through the "SDEL" batch file using "TEST.txt" as SDEL's file parameter. (SDEL.bat was presented here as the previous example batch file.)


--------------------------------------------------------------------------------

============================================================================================================



Automating Shutdown
This hack allows you to shut down windows at predetermined times with the Task Scheduler

Contributed by: cedricktattoo
[03/19/05 | Discuss (12) | Link to this hack]


After buying a new external hard drive to back up my PC, I wanted to set up my system to automatically back up my hard drive and then shut the computer down for the night once a week. This seemed like an easy task until I actually tried to set the Task Scheduler to shut down my computer. No problem getting things to automatically back up, but there didn’t seem to be any way to get Task Scheduler to shut the computer down. I tried pointing the scheduler at the shutdown.exe in the system32 folder, but all I got was a momentary flicker on my screen, and the computer failed to shut down. I then tried to bastardize Hack #6 from the first edition of Windows XP Hacks by creating a shutdown shortcut on the desktop and then pointing the Task Scheduler at that. No dice. All I got was another screen flicker and the computer continued to happily run.


Frustrated, I went to the internet, but all I really there found were sites advertising shutdown programs I had to pay good money for (sometimes quite a bit of money). I thought the idea of spending $20 dollars just to get my computer to turn off seemed like a terrible waste of cash for such a simple request from my operating system. Then I arrived at the idea of using a batch file.

I worked out how to automate the shutdown procedure with a batch file as follows:



1) Go to the Shutdown menu and open the DOS prompt

2) type: "edit powerdown.bat" (without the quotes)

3) you will get a bluescreen interface. At the blinking prompt, just type: "shutdown –s" (without the quotes)

4) save and exit the bluescreen



At this point, you will have a file named "powerdown" in your "Documents and Settings" folder under your user profile. Now all you have to do is go to the "Scheduled Tasks" utility in the "Systems Tools" folder and set up the time and frequency you want the batch file to operate. You can name the batch file whatever you want, but whatever you do, do not name it "shutdown.bat" when you create it because this, for some reason, just makes the file create an endless loop in a DOS window.

I hope this helps out. I can see how learning a little DOS and practicing with batch files can save a lot of money.

--Cedrick May

=====================================================================================================================

Schedule Task Shutdown
2008-08-26 00:31:17 m_colin [Reply | View]


I need to have the computer shutdown at 11:00 PM because my son stay late in the pc.

I created a batch file and attached it to the schedule Task. It did not resolve the issue. When I read that you created a batch file C:/windows/system32/shutdown.exe /s /t 30 for your server I want to try it.

MC
shutdown
2007-01-28 05:21:31 nudsaq [Reply | View]


shutdown will bring your computer to the "Your computer is now ready to be turned off" stage but will not power down. To power down try creating a batch file with:

tsshutdn /powerdown

This will turn power off your computer's power if it supports advanced power management.

http://support.microsoft.com/?kbid=320188
shutdown
2006-06-22 09:55:43 eljefemus [Reply | View]


I have a computer in a domain, how I automated shutdown was open a notepad file. I typed C:/windows/system32/shutdown.exe /s /t 30 then saved as a batchfile, then went to scheduled tasks and pointed a new task to the batch file
shutdown
2006-06-22 09:55:41 eljefemus [Reply | View]


I have a computer in a domain, how I automated shutdown was open a notepad file. I typed C:/windows/system32/shutdown.exe /s /t 30 then saved as a batchfile, then went to scheduled tasks and pointed a new task to the batch file
automatic shutdowns
2005-09-13 06:50:54 justAL [Reply | View]


As I know it, there are two stages to a shutdown.

One is "shutdown" which shuts down WINDOWS XP, but the computer itself is still on.

Before I had Patch 2 my WINDOWS XP would shut down, and turn off the computer, now it just shuts down, and I have to turn off the computer manually.

I'll try this new batch file and see if it works..


automatic shutdowns
2005-09-13 11:45:31 maggietoo9 [Reply | View]


I used to do a lot with batch files when DOS was the OS, but its been a looong time.

What do you mean, go to the "shutdown menu" and open a DOS window? Does that mean go to the Start Menu and choose RUN and then do something? How do I get to a DOS window?

Thanks,
Maggie
Sounds Good, but didn't work properly.
2005-04-23 06:15:16 JGTOReilly [Reply | View]


My sysetem's OS is Windows XP Pro. This hack was exactly what I was looking for and it sounded logical. I set it up per the directions, but it didn't work. All it does when I try to run the BAT is flash a DOS screen on up so fast I can't even tell if it says anything. Is something missing in the directions? I have created a BAT file called PowerDown.BAT. The file contains one line with the word "shutdown-s" (no quotes). Shouldn't there be a comand before the action? Thanks
Sounds Good, but didn't work properly.
2006-05-15 17:27:58 viberg220 [Reply | View]


you need to have a space between shutdown and -s
OS: XP Pro Update
2005-04-23 06:51:10 JGTOReilly [Reply | View]


I should have investigated this Hack a little more thoroughly, before my last post. The BAT file line should read "shutdown.exe -s" (with no quotes), for the hack to run properly in an XP Pro environment. Everything else is as the original author states. Follow his directions and use “shutdown.exe -s" (with no quotes) in place of his suggestion for the BAT file line and you should have a BAT file that you can have your Task Scheduler run it at your specified time. Hope this hack helps more. I used this Hack to shutdown my computer at a specific time and it worked flawlessly in my XP Pro environment. I didn’t test it in any other OS’s. Be sure to turn off the scheduled task when you don’t what it to function.
Slick no frills easy logical hack!
Your Welcome

OS: XP Pro Update
2005-05-12 08:48:29 cedricktattoo [Reply | View]


Very interesting. I use XP Pro, too, and this hack works perfectly as I originally wrote it for my XP system. It's even worked on other XP Pro systems used by a couple of friends. However, if substituting "shutdown.exe -s" still allows the hack to work for you and others, cool! The actual DOS command is "shutdown" and not "shutdown.exe," so it would be interesting to investigate why "shutdown.exe" worked on your system but "shutdown" did not. Has anyone else ever had this problem, I wonder?
OS: XP Pro Update
2005-09-12 20:29:44 Overlord [Reply | View]


Typing "shutdown" will run either Shutdown.bat, Shutdown.exe, or Shutdown.com. Since you named the batch file shutdown.bat, the command "shutdown" (without an extension) in the batch file makes it run the batch file over and over, as in; hey, run shutdown.bat. If you name the batch file anything else such as "KillPC.bat you will have no problems with Winders getting confused over which file to run.
OS: XP Pro Update
2005-05-24 20:26:47 kewlbreeze [Reply | View]


I am working on it now will let you know what
happens
===========================================================================================================================



THE BATCH FILES

CDD.bat

("Change/Display Directory" Bat)
Syntax: CDD (Directory Name)

:: CDD.bat
::
:: Changes to a Specified Directory
:: Displays a File and Subdirectory List
::
@ECHO OFF

CD %1 "%1" Represents the Directory Name.
You Type at the Command Line.
ECHO. Adds a Blank Line to the Display.
C:\BATCH\DR
________


CLU.bat

("Clear Screen - Move Up" Bat)


:: CLU.bat
::
:: Moves Up One Directory Level
:: Displays Directory on a Cleared Screen.
::
@ECHO OFF

CD..
CLS
ECHO. Adds a Blank Line to the Display.
C:\BATCH\DR
________



CFB.bat

("Copy From `B'" Bat)
Syntax: CFB (Optional File name)

:: CFB.bat
::
:: Copies All or Specified Files From the
:: B Drive Root to the Current Directory
:: (A Sub-Directory Location May be Specified)
:: (Hidden Files are Excepted.)
::
@ECHO OFF
ECHO. Leaves a blank line for separation.

IF "%1" == "" XCOPY B:\*.* If there is no file name, all
IF NOT "%1" == "" XCOPY B:\%1 files in the B drive root will
ECHO. be copied.
C:\BATCH\DR If there is a file name, only
it will be copied.
________



CTB.bat

("Copy to `B'" Bat)
(Substitute a USB flash-drive
letter to copy to it.)

Syntax: CTB (Optional File Name)

:: CTB.bat
::
:: Copies All or Specified Files to a B-Drive Floppy
:: (Hidden Files are Excepted.)
::
@ECHO OFF

ECHO. Adds a Blank Line to the Display.
IF "%1" == "" XCOPY *.* B:\ If there is no file name, all files
IF NOT "%1" == "" XCOPY %1 B:\ in the current directory will be
C:\BATCH\DR B:\ copied.
If there is a file name, only
it will be copied.


________



DAF.bat

("Delete All Files" Bat)


:: DAF.bat
::
:: Deletes All files in the Current Directory
:: With Prompts and Warnings
::
:: (Hidden, System, and Read-Only Files are Not Affected)
::
@ECHO OFF

DEL . `.' Represents the Current Directory.
DR



DAF.bat
(Variation)

("Delete All Files" Bat)

:: DAF.bat (Variation)
::
:: Deletes All files in the Current Directory
:: Skips "Are You Sure?" and Other Messages
:: (Hidden, System, and Read-Only Files are Not Affected)
::
@ECHO OFF

ECHO Y | DEL . > NUL Echoes (sends) a "Yes" Answer to
the "Delete" Prompt and Hides
Other Messages.
ECHO. Adds a Blank Line to the Display.
C:\BATCH\DR


________



DELE.bat

("Delete Except" Bat)
Syntax: DELE (File name) to Not be deleted)

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

MD SAVE Makes a Temporary "SAVE" Directory.
XCOPY %1 SAVE > NUL "> NUL" Suppresses On-Screen Messages.
ECHO Y | DEL . > NUL Deletes all Files in the Current
Directory showing no Prompts.

MOVE SAVE\*.* . > NUL Returns Excepted File(s) to the
RD SAVE Current Directory.
Removes "SAVE" Directory.
ECHO. Adds a Blank Line to the Display.
C:\BATCH\DR Displays the Results of the Operation.


To see a variation of this batch file which will allow multiple files of differing names to be excepted, go to Advanced Batch Files.


--------------------------------------------------------------------------------

DELT.bat

("Delete Tree" Bat)
(Requires DOS 6 or Newer)

Syntax: DELT (Directory Name)

:: DELT.bat
::
:: Deletes Specified Directory and All Files
:: and Directories Below
:: Prompts "Are You Sure?" Before Deletion Commences.
::
@ECHO OFF

IF "%1" == "" GOTO NO-DIRECTORY Prompts if No Directory was Specified

ECHO. Displays a Blank Line.
ECHO. Displays a Blank Line.

TREE %1 Displays the Directory Structure
to be Deleted.
DELTREE %1 Deletes Directory Structure.
DR
GOTO END Directs DOS to End the Batch File
Operation.

:NO-DIRECTORY
ECHO.
ECHO No Directory Specified
ECHO.

:END
________



MCD.bat

("Make/Change Directory)
Syntax: MCD (File Name)

:: MCD.bat
:: Makes and Changes to the Specified Directory
::
@ECHO OFF

CLS
MD %1
CD %1
________



MDEL.bat

("Multiple Delete" Bat)
Syntax: MDEL (File Name File Name File Name, etc.)

:: MDEL.bat
:: Allows Deletion of Up to Nine Files
:: with Different Names and Extensions
:: Wildcards are Permitted
::
@ECHO OFF

CLS Clears the Screen.
FOR %%F IN (%1 %2 %3 %4 %5 %6 %7 %8 %9) DO DEL %%F See Text.

ECHO. Adds a Blank Line to the Display.
C:\BATCH\DR Confirms the Operation.

This uses the DOS "FOR-IN-DO" (FOR) command and replaceable parameters. Basically, it means "FOR each Item INside the Brackets, DO the given command". In this case, it will take each file name you give at the command line and substitute it for one of the percent-numbers. These percent-numbers are replaceable parameters, with "%1" representing the first file name, "%2, the second, and so on. Wild card characters, ` ? ' and ` * ', may be used in file names.

The batch file deletes each item inside the brackets, which will be those file names you typed at the command line. Each file name is substituted for one of the percent numbers. You may specify up to nine file names or groups.


MDEL.bat (Improved)

("More Powerful "Multiple Delete"" Bat)
Syntax: MDEL (File Name File Name File Name, etc.)

:: MDEL.bat (Improved)
:: Allows Deletion of Multiple Files
:: with Different Names and Extensions
@ECHO OFF

CLS Clears the Screen.

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

ECHO. Adds a Blank Line to the Display.
C:\BATCH\DR Confirms the Operation.

This version allows one to type as many file names as the command line can hold. It uses the "SHIFT" command. That allows each file name on the command line to shift down one number to become the first replaceable parameter. Thus, the second file name will become "%1" after the SHIFT command is issued, the third file name becomes "%2", and so on. After yet another SHIFT command, the third file name will be in position "one" (%1). As long as there are file names left on the command line, they will be shifted one at a time into position number `1'. Then, each is deleted in turn with an on-screen message to that effect being displayed.

Finally, when no file names are left, the "IF NOT" statement becomes false because "%1" will then be equal to nothing. Thus the batch file does not loop to "AGAIN" and instead goes on to display the directory listing confirming the files are gone.

________



MU.bat

("Move Up" Bat)
Syntax: MU (File Name File Name File Name, etc.)

:: MU.bat (Move Up)
:: Move All or Specified Files Up One Level
::
@ECHO OFF

If "%1" == "" GOTO MOVE-ALL
If NOT "%1" == "" GOTO MOVE-SPEC

:MOVE-ALL
MOVE /-Y *.* ..
GOTO END

:MOVE-SPEC
FOR %%F IN (%1 %2 %3 %4 %5 %6 %7 %8 %9) DO MOVE /-Y %%F ..

:END
ECHO. Adds a Blank Line to the Display.
F:\BATCH\DR
________


This allows one to move up to nine files or file groups into the parent directory one level up. I use it because I have many directories in which there is a WORK subdirectory. After doing my work, I want to move the completed files into the parent directory and use this batch file to do so. The "/-Y" will prompt you if any files in the parent directory are about to be overwritten. You may choose to overwrite or not. The batch file will then resume and go on to the next file. (Be aware, some DOS versions do not recognise this switch and will overwrite without prompting.)

You may modify this batch file into CU.bat (Copy Up) by replacing the MOVE commands with:

COPY *.* .. /-Y

or

COPY %%F .. /-Y .

Note that the "Overwrite" switch comes at the end of the line when COPY is used.

________



SDEL.bat

("Safe Delete" Bat)
Syntax: SDEL (File name)

:: SDEL.bat (Safe Delete)
:: Displays File to Be Deleted
:: Prompts to Delete File or Abort Operation
:: Wildcards May be Used to Delete File Groups
::
@ECHO OFF
CLS

IF NOT "%1" == "" GOTO DISPLAY

ECHO.
IF "%1" == "" ECHO No File(s) Specified! Prompts if No File
ECHO. is Given.
GOTO END

:DISPLAY
ECHO %0 %1 Gives the Batch File Name
ECHO. and File to be Deleted.
ECHO These Files Will Be Deleted:
ECHO.
DIR %1 | FIND "Directory" Displays the Path and
DIR %1 /B /P Files to be Deleted.

ECHO.
ECHO To Delete Listed Files, Allows the User to
ECHO Press Any Key Continue or Abort.
ECHO.
ECHO To Cancel, Press: `Control-C'
ECHO.

PAUSE > NUL

:DELETE Deletes Selected File(s).
DEL %1
ECHO.

:END
ECHO. Adds a Blank Line to the Display.
C:\BATCH\DR Confirms the Operation.


An improved SDEL.bat may be found in Advanced Batch Files.

________



STEP.bat

("Step" Bat)
(Requires MS-DOS 6.2 or Newer)
Syntax: STEP (Batch File Name with No Extension, Parameters)

:: STEP.bat
:: Allows one to Step through a Batch File
:: To Test Each Line
::
@ECHO OFF
COMMAND /Y /C %1.bat %2 %3 %4
:END
________


This simple example allows one to run a batch file a line at a time to test it. It runs another copy of DOS' COMMAND.com. The "/Y" switch is what does the stepping. It displays each line and asks if you wish to run it or not by pressing "Y" or "N". You may exit this procedure at any time by pressing "CONTROL-C". Also, by pressing "Escape", the batch file will continue on its own from the current line.

The "/C" switch runs the specified command and then returns to the base COMMAND.com - either after the stepping procedure finishes, or after pressing "CONTROL-C".

When running this batch file, don't type the ".bat" extension. STEP.bat does that for you via the "%1.bat" replaceable parameter. If the batch file requires additional parameters, you may specify up to three via the " %2 %3 %4" replaceable parameters. Here's a syntax example:

STEP SDEL TEST.txt

This will step through the "SDEL" batch file using "TEST.txt" as SDEL's file parameter. (SDEL.bat was presented here as the previous example batch file.)


--------------------------------------------------------------------------------

=============================================================================================================================


"What is a batch file and why might I need one?"
A batch file is a series of commands that you might ordinarily issue at the system prompt in order to perform a computer operation. The most common uses are to start programs and to run utilities. Batch files do that with one command instead of the multiple commands usually required. They can be likened to shortcut icons as seen in point-&-click operating systems, but batch files are much more powerful.

Using a batch file to start a program often means that your path statement may be made shorter. This means fewer directories through which DOS must search during its operations. Having a shorter path will also leave room for other programs which may require path inclusion in order to function properly.

Further, sophisticated batch files can improve upon program starting by loading all or part of the program into upper or expanded/extended memory, thus freeing up more lower (conventional) memory. Allowing lots of lower memory means your programs have breathing room and there will be space for utilities to run. This same capability may be had at the command line, but the commands will likely be intricate and difficult to remember. Why not let a batch file do the work for you?

With one command, a batch file can start the program in the desired configuration and in addition, can request an associated file such as a word processor document or spreadsheet be loaded once the main program is running. This saves the user a search for that document and the issuing of the commands necessary to load it. One simple command of the user's naming does it all.

This is similar to Window's "File Association" feature, but with more advantages because a number of batch files could be written to load the same file each with its own, but different, attributes or start-up options. In fact, one could even have the same file loaded into different programs, each time with specific, yet different, options. The user never has to change these configurations manually. To reinforce: once set up, these batch files can load any program, with or witout documents, in the user's chosen configuration automatically and with the user's choice of options.

Using a batch file to run a utility means being able to have direct access to that utility. If there are any often-used specific options, they can be included in the batch file and thus save you from typing, with the possibility of mis-typing, these parameters.

DOS batch files can also make decisions to perform operations only if certain conditions exist or don't exist. The most sophisticated ones can even emulate commands not normally available with the DOS operating system.




WHAT YOU'LL BE DOING:
The first section, below, will help you to understand and then write basic batch files. For those who are afraid of programming, this article will show you how simple it really is. DOS batch files are a good place to start learning programming because they use plain-English commands for the most part. Thus, they are easier to comprehend, even for those of you whose first language is not English.

You may then move on to other sections which will show you to how improve a batch file, and to make it look attractive & easy to decipher when looking back at it from some future point. You'll also see how to combine small batch files to do larger things.

On the Advanced Batch Files page, you'll be shown more complicated example batch files which use command-line parameters. These allow the file to function in different ways depending on the circumstances and the desired outcome. On the other advanced pages, there are batch files given that prompt a user for input. These permit operations based on choices made by the user after the file is running.


RENAMING
You may wish to rename the example files and perhaps use a different path structure. Go ahead - this tutorial is just for example purposes. You may also see another use for a batch file if it had some modifications. Be creative and try the changes; however, be aware that no responsibility will be taken by Doctor DOS for any problems encountered when using (or mis-using) anything presented here.


TESTING
I suggest that you always try out any batch file in a TEST directory. Copy some files there to try out the batch. If it works as you intend, and more importantly, if it does not work as you do not intend, then transfer it to your regular working batch directory. If anything did go wrong in the TEST directory, it would only affect copies of files and not corrupt or destroy the originals.




GETTING STARTED:
First realise that a batch file typically takes the following form:

* Get Ready to Use a Program or Utility
* Run a Program or Utility
* Verify and/or Clean Up and/or Restore


The first line above, means to give some initial instructions that prepare the main program or utility to run. These might be to go to a specific directory, create or change an environment parameter, place a message on to the screen, or anything else required for the program/utility to run as you or it requires, as dictated by the task to be done.

The next line runs the program or utility as directed by you, or in some cases, by the batch file itself under the guidance of some pre-selected criteria.

Finally, the last line can be used to display closing messages or a directory listing as confirmation of a utility operation. It might delete temporary files made by the batch file, or it might restore the program or DOS to its default settings. Another use would be to deposit the user in some specific directory after the program or utility has finished, or return one to where one was before running the batch file.




"What do I do first?"
To begin, create a directory called "C:\BATCH" where you will place your new batch files. Some people use "C:\BAT", but that bothers me because there would then be a directory with the same name as the batch file extensions, which must use ".bat". For housekeeping and organisational purposes, I try to not use names more than once - especially where conflicts might arise or confusion might be generated.


PATH STATEMENT
Next, modify your path statement as found in your "AUTOEXEC.BAT" file to include this new directory. Use the text editor that came with DOS. I suggest placing it near the start so that DOS will find and execute your batch files quicker by not having to search through unnecessary directories first. I have my "Batch" directory placed second right after the C:\DOS directory. So the path statement would read in part: PATH=C:\DOS;C:\BATCH; and so on. It's also important that the BATCH directory be before any program directories. This is because any program executable with the same name as the batch file will initiate first, bypassing your carefully crafted batch commands. After saving this file, type "C:\AUTOEXEC" and press "ENTER", or reboot to initiate the change.


TEXT EDITOR
After the AUTOEXEC.BAT completes, select a text editor to use in writing each line of your file. You may employ the one you used above, but there are many other text editors available that you may find are more to your liking. The only thing required is that it be able to save these files in plain DOS (ASCII) text. This can be done by all text editors such as DOS' Edlin and Edit, Windows Note/Wordpad, and a host of independent editors. Word processors like Wordstar, WordPerfect and MS Word also have the capability as long as you save the document in ASCII (plain text). I personally like to use a little text editor called "Tiny Editor" by Tom Kihlken.

Type the files into your text editor as you see them here. DOS is not case sensitive except in certain instances. These will be noted if necessary. Otherwise, one may type all upper, all lower, or some combination. I prefer to use all-caps for this purpose, except for certain instances, or when case sensitivity is an issue. Alternatively, you may screen capture or download this page and edit everything out but the batch file(s) you wish to use.

When finished, name the file as seen here or use some other name that you'll remember and be able to associate with the batch file and what it does. Be sure to stick to DOS file-naming conventions of up to eight characters before the dot and using a ".BAT" extension so that DOS will know it's a batch file and run it as such. Newer DOS versions allow longer file names but I don't recommend their use. Besides causing extra typing in order to run the file, if you decide to use it yourself on an older system, or pass it on to someone using an older DOS version, a long file name may cause problems.


NAMING
Recalling the file-name conflicts I touched upon farther back, you should not name your batch file the same as any other file which is on your computer, if possible. Otherwise, whichever comes first during a DOS path statement search, will execute. This is unless one is in the directory in which the given file resides. In that case, the current directory's file takes precedence. There may be some cases where one wishes to use a batch file with the same name as another file, but to eliminate unexpected results, it's generally best to not use files with the same names. For programs, however, I do tend to use the same name as the given program's executable unless it is a long name. This is not generally a problem because I have no program directories in my path and never manually run programs from their own directories.

Finally, remember to place your new file into your "C:\BATCH" directory.



Once you understand the basics, we'll discuss some
improvements to make the file do more things with
the same simple keyboard command. This technique
will be followed throughout these lessons.





YOUR FIRST BATCH FILE:
Let's select a task that involves only a few steps. I use WordPerfect a lot, so we'll do that one first. Ordinarily, without a batch file, one would log onto the appropriate drive, change to the WordPerfect directory, and then issue the command to start WordPerfect. A batch file will do this for you automatically. As you will see, each main line in the batch file emulates what one would ordinarily type when at the command line.

I'll first show you the complete batch file and then explain what each line does. The following assumes that you are using WordPerfect 6.0 and that it resides in a WP60 directory on the `C' Drive. Change these parameters, if they differ from your word processor and directory.

Note that the indents shown for each example are to make them stand out in your browser. You don't need to indent the lines in the batch file itself unless you want to use them as part of your batch file layout. Indents made by tabs or spaces after "ECHO OFF" are ignored by DOS during batch file execution.

:: WP.bat
:: Runs WordPerfect
::
@ECHO OFF

C:
CD\WP60
WP

The first line is the batch file name. This is useful to remind anyone looking at the file which one it is. The second line is a title remark that tells what the file does.

Note the use of twin colons. DOS will not execute any batch file line with twin colons in front of it, nor display it on the monitor screen. After seeing the second colon, DOS ignores anything following and goes to the next line. That is because the colon is an illegal label character. With regards to batch files, a DOS "label" is a word or a series of numbers/characters used to identify a part of a batch file. Some people use a single colon to place remarks in a batch file, but since DOS uses this to identify its labels and those lines will be read, I suggest the single colon not be used, except of course, as a label precursor. (You'll see more on labels in the tutorial's examples.)

Alternatively, others will use "REM" which is short for "Remark". DOS does not execute these lines either, but it does read them, slowing things down. This is not a problem with today's fast processors and hard drives, but can make a difference on slower computers when the batch file is long and contains a lot of remarks. Regardless, my philosophy is that anything which speeds things should be used.

I must mention there is a also a problem with "REM" lines which contain redirectors and piping, which I won't get into here because that is beyond the scope of this tutorial. I simply recommend the double colon as the best symbol for placing remarks/comments into a batch file.

Getting back to the example batch file, for the third line I employ the double colons with the remainder of the line blank. It is used as a separator between the title and the file itself. Although they do not affect the running, or contribute to the mis-running, of the batch file, they should be used here because DOS will display an unnecessary prompt on the screen for any blank line before an "ECHO OFF" command.

The fourth line is required to tell DOS not to display the succeeding lines on the screen, and the "@" symbol tells DOS not to show the line itself. The first command in typical batch files usually is "ECHO OFF". "Echo" means that the keys struck on the keyboard are "echoed" (displayed) on the screen. Since a batch file is just a series of commands, what is typed in the file would be echoed on the screen as DOS executes each of those lines, just as though you were typing each instruction at the command line. However, in most cases, the user is only interested in the end result and does not need to see everything that DOS is doing. Using the "Echo Off" command means each command issued by the file as it works toward completing the requested task will not appear on the screen. Again, if you wish even that line to be hidden, add the "at" sign ( @ ) before it, as in the example above.

Next is a blank line. DOS ignores blank lines (if they occur beyond an "Echo Off" command), and executes the following line immediately. I insert such lines to separate the various steps the file does to complete its assigned task. It makes no difference to the running of the file but does give each part its own space, making for better readability. This is important for lengthy, complicated files, especially if you go back into them a long time after they were written.

The succeeding line tells DOS to go to the `C' drive. This is important if you are on a floppy, CD-ROM, RAM, Flash, or another hard drive, yet wish to start word processing immediately. The next line changes to the WP60 directory and the final line tells WordPerfect to start.

There you have it. Save that as "WP.BAT" in your BATCH directory. Now to start the program from the DOS prompt, type "WP" from any drive. If it works, you may now remove "C:\WP60;" from your path statement, making for a more efficient running of DOS. Since the batch file changes to the correct directory for WordPerfect, DOS does not have to search the path to locate the WP executable file. Since it no longer has to search, having WordPerfect in the path statement is unnecessary. The fewer directories through which DOS must search, the faster it locates what it wants, resulting in a more efficient, and thus faster, operation of your computer.

Note that you should be sure you have told WordPerfect
where its files are via the program's set-up section.
Removing the WordPerfect directory from the path may
result in some error messages while running WordPerfect
if this has not been done. Typically, pressing Shift-F1
will display the set-up screen when in WordPerfect.





IMPROVEMENTS: "Can this file do more work for me?"
I have a screen that is my opening one after boot-up and it's the one to which I always return after exiting any program, save for a few. It's my desktop, which for me, is the `C' drive root directory with a specific custom prompt and a directory listing using an after-market program called Color Directory by Loren Blaney. It gives a wide-format display of the contents of the directory with sub-directories and file types in different colours. You could display the directory contents by incorporating DOS's "DIR" command, if you wish, but Color Directory dresses up the screen and makes it easier to discern file types.

To return to this example desktop after exiting Wordperfect, the screen must be cleared, the `C' Drive root directory must be returned to and the Color Directory listing displayed. Now, we could add these commands to the end of the above batch files, but since I add it to most batch files I write, it's a better idea to make this its own batch file and then have each initial batch file refer to this new one as part of its list of commands. It will save typing those commands into every batch file and should you decide to change your desktop, only this one specific file needs to be altered, because all others will refer to this one.


Let's write the new file first:

:: CLR.bat
:: Clears Screen and Returns to the DeskTop
::
@ECHO OFF

C:
CD\
CLS

C:\BATCH\DR.BAT

We have already discussed the opening information lines, the "@ECHO OFF" command, the double colons and blank lines, so I will skip them here and for all future discussions. Lines 6 & 7 return one to the `C' Drive's root directory. Line 8 is DOS's "Clear Screen" command. It erases everything on the screen except for the prompt and any special screen settings contained within, such as certain coloured text & backgrounds, among other options.

The final command is for the Color Directory. It's also a batch file (called "DR.BAT") with one line (after "@ECHO OFF") that directs DOS to the directory containing the Color Directory program's executable file. The full path is given so that DOS will not have to search any directories for the "DR" batch file. I have named this batch file "CLR.BAT", which stands for "Clear Screen, Return to Desktop".

I can now add this "CLR" command to the end of any batch file to clear the screen and return me to my desktop automatically after completing any task. The reason this works is that after a DOS batch file hands control over to a program, when the program finishes, it returns the reins to DOS which remembers that there is another line in the batch file to run. It therefore runs the "CLR" batch file upon exiting a given program, which then returns me to my desktop.



Using our word processing example farther back,
the file now looks like:

:: WP.bat
:: Runs WordPerfect and Returns to the Desktop
::
@ECHO OFF

C:
CD\WP60
WP

C:\BATCH\CLR





FURTHER ENHANCEMENTS: "Could this file do yet more work?"
The preceding improves the original "WP.BAT", but we can enhance it further through WordPerfect's built-in command-line options. I won't get into an explanation of those options here as that would be outside the subject of this article. You'll need to consult the WP manual to learn more; however I'll give you an example of some.

I like to have WordPerfect use expanded memory (/r), and have it place & read its overflow, buffer, & temporary files on my RAM (F) Drive (/d-) for faster operation and the freeing of lower (conventional) memory. With these options, the batch file then becomes:

:: WP.bat
:: Runs WordPerfect and Returns to the Desktop
::
@ECHO OFF

C:
CD\WP60
WP /r /d-F:\TEMP

C:\BATCH\CLR

Note to use this, you will have to create a TEMP directory on your RAM drive upon each bootup. Add such a line to your Autoexec.bat. If you don't make use of a RAM drive (and you should!), create the TEMP directory on your C drive and point WordPerfect there. It won't be as fast, but there will be fewer files for WordPerfect to look through when it doesn't place its temporary files in its own, already crowded directory.

WordPerfect, like many DOS programs, can also load a document upon startup. You might like to use a letter form (which is called a "template" in the word processing world) for most letters you type. Its name might be "LETTER.FRM" and it would likely include your name & address as a header, along with various options you like to use. (Never use the extension "TMP" for a "template" file as that may be used by DOS and its programs to designate a temporary file). If it's sitting in a subdirectory of WordPerfect's called "Template", the third-last line of the batch file becomes:

WP /r /d-F:\TEMP C:\WP60\TEMPLATE\LETTER.FRM


This batch file version might be called "WPLET.BAT".

Now that you have this basic batch file, a large stable of batch files could be written to run WordPerfect and load any number of different documents. In addition, you may also have your batch file start a WordPerfect macro using the "/m-" switch. A macro is a type of batch file used by many programs. You write it much as you would these DOS batch files except a ".WPM" extension is used in Wordperfect. (See your word processor's manual for details on macro writing.)

To run a WordPerfect macro from your DOS batch file, enter the macro option after any other options for WordPerfect. Now, with one simple command, you could start the program from anywhere within DOS, load a letter template, and then have the WP macro load the current project on which you are working into that template. The line might then look like:

WP /r /d-F:\TEMP C:\WP60\DOCUMENTS\LETTER.FRM /m-PROJECT.WPM

All this is from one simple batch file that might be named "WPCP.BAT" for "Wordperfect, Current Project". What a huge amount of typing saved! Can you imagine typing those lines every time you wanted to work on that particular project? Plus, with this method, you get the options you want, tailored to each type of program and document upon which you are working, without having to reconfigure a program's defaults.

Note that these command-line options are done using "slash switches", that is a slash followed by a letter or character string. For more on this aspect of DOS, see DOS Switches, elsewhere at this website. Making use of command line options (switches) is a very powerful way to run programs.



When you are finished with one current project, rewrite the WordPerfect macro to refer to your next project. This way, the same DOS batch file will always start your current project regardless of what it is. This saves having to remember, or look up, a new batch file name for each new project.





If you always load the current project into the same template (which would be typical), after the first time, save the project and template as one, under the project name. Then redo the batch file to have WordPerfect load the project file directly, rather than having it load a template and then run a macro to load the project into that template. It saves a step and gains a small speed advantage.




In closing, a batch file may be made up
from any system prompt commands.
This allows one to funnel multiple-line
typings down to just one simple command.

Batch files put one on the way to power-user status! As you go through the example pages at this website, you will often see the same batch file fragments used over & over. As you become proficient at writing them, you will begin to build a DOS toolbox of batch techniques that can be mixed & matched to achieve the desired results so you can then automate any task that you attempt.


--------------------------------------------------------------------------------
==================================================================================================================
How to shut down / restart the computer with a batch file.
Issue:
How to shut down / restart the computer with a batch file.

Reasoning:
It may be necessary after a batch file is completed its copying or installing process to restart the computer to complete that installation. Below are steps that can be used to restart a computer through a batch file.

Solution:
MS-DOS Users

If the computer needs to be restarted from MS-DOS please see our debug page for additional information on how to do this.

Windows 95, Windows 98 and Windows ME Users

Restarting the computer

START C:\Windows\RUNDLL.EXE user.exe,exitwindowsexec
exit

Shut down the computer

C:\Windows\RUNDLL32.EXE user,exitwindows
exit

NOTE: When typing the above two lines, spacing is important. It is also very important that the exit line be placed into the batch file as many times Windows may be unable to restart the computer because of the open MS-DOS window.

Microsoft Windows 98, and Windows ME users may also perform the below command to perform different types of rebooting or shutting down.

rundll32.exe shell32.dll,SHExitWindowsEx n

Where n is equal to one of the below numbers for the proper action.

0 - LOGOFF
1 - SHUTDOWN
2 - REBOOT
4 - FORCE
8 - POWEROFF
Windows XP users

Microsoft Windows XP includes a new shutdown command that will enable a user to shutdown the computer through the command line and/or batch files. Additional information about this command can be found on our shutdown command page.

Additional information:
Additional information about the rundll and rundll32 files can be found on document CH000570.
===============================================================================================================

Hello,
I registered here asking for a bit of help. First off I am very new to this language and i need to make a little program off a batch file. I found out how to shutdown the computer using a batch file.. and how to set a specified time to shut off... the only thing that is in my way.. is basically.. that is all i can do really..

1st it would be nice if someone could help me with some commands... What i want is to have a menu with choices displayed after the batch file is launched that gives you 3 things to choose from.. shutdown in 15 minutes.. shutdown in 30 minutes or shutdown in 60 minutes.. so far all I have is..

Code :

shutdown -s -f -t 300

-(300) is 300 seconds
Yea thats pretty much what i am limited to.. it would be really great to have some help on this. Thanks in advance.

Ryan




Report Offensive Message For Removal



Ads by Google

Mp3 accessories
covers, skins, FM Transmitters We stock accessories for all Mp3's
www.i-nique.com




Response Number 1

Name: CWoodward
Date: February 10, 2006 at 20:09:48 Pacific

Reply: (edit)
Try this:

@ECHO OFF

CLS

:Start
ECHO When do you want to shutdown?
ECHO Press number of choice followed by the Enter key
ECHO 1: Fifteen Minutes
ECHO 2: Thirty Minutes
ECHO 3: Sixty Minutes
ECHO 4: Quit

SET Choice=
SET /P Choice=""

IF '%Choice%'=='1' GOTO Fifteen
IF '%Choice%'=='2' GOTO Thirty
IF '%Choice%'=='3' GOTO Sixty
IF '%Choice%'=='4' GOTO End
CLS
ECHO "%Choice%" is not valid
ECHO Try again
GOTO Start

:Fifteen
SHUTDOWN -S -F -T 900
GOTO End

:Thirty
SHUTDOWN -S -F -T 1800
GOTO End

:Sixty
SHUTDOWN -S -F -T 3600
GOTO End

:End
CLS



Report Offensive Follow Up For Removal



Response Number 2

Name: CWoodward
Date: February 10, 2006 at 20:12:13 Pacific

Reply: (edit)
You can delete the line:

IF '%Choice%'=='4' GOTO End

If you don't want the shutdown to be optional.




================================================================================