Thursday, 21 March 2013

Batch file creation

                                        Batch file creation
Batch file ABCs
Batch files allow MS-DOS and Microsoft Windows users to create a lists of commands to run in sequence once the batch file has been executed. For example, a batch file could be used to run frequently run commands, deleting a series of files, moving files, etc. A simple batch file does not require any special programming skills and can be done by users who have a basic understanding of MS-DOS commands.
A good example of a batch file for someone who is more familiar with Windows or the MacOS is to think of a batch file as a shortcut in Windows or an icon on the MacOS. Much like a shortcut, batch files could be used to run one or more commands or programs through the command line.
Another example of a very well known batch file is the autoexec.bat, which is a boot batch file loaded each time the computer boots into MS-DOS and early versions of Windows. This batch file contained all the necessary commands and programs used to run MS-DOS and Windows each time the computer booted.
Creating a batch file
MS-DOS users
To create a basic batch file in MS-DOS, follow the below steps that give you an example of how to create a basic batch file.
  1. Open an MS-DOS command window or get to MS-DOS.
  2. At the MS-DOS prompt, type: edit test.bat and press enter.
  3. If typed properly, you should now be in a blue screen. Within the screen, type:

    pause
    dir c:\windows
    dir c:\windows\system
Once the above three lines have been typed in, click File and choose exit; when prompted to save, click "Yes." Users who do not have a mouse cursor can accomplish this same task by pressing ALT+F to access the file menu, then pressing "X" to exit, and pressing enter to save changes.
Once you are back at the MS-DOS prompt, type: test and press enter. This will execute the test.bat file and begin running the file. Because the first line is pause, you will first be prompted to press a key. Once you press a key the batch file will run line-by-line; in this case, listing the files in the windows and windows\system directories.
If you wish to add more lines to this batch file you would type "edit test.bat" to edit the file again.
Additional information about the MS-DOS edit command can be found on our edit command page. Some versions of MS-DOS and bootable diskettes may not have the edit command; if this the case, you would either need to obtain the edit.com file to access this file or use the copy con command.
Microsoft Windows and other users
A Windows user can still use the above MS-DOS steps if they wish to create a batch file. If, however, you're more comfortable using Microsoft Windows or your operating system, you can use any text editor, such as Notepad or Word pad, to create your batch files, as long as the file extension ends with .bat. In the below example we use the Windows notepad to create a batch file.
Click Start
Click Run
Type: notepad and press enter.
Once notepad is open, type the below lines in the file or copy and paste the below lines into notepad.

@echo off
echo Hello this a test batch file
pause
dir c:\windows
Click File and click Save; browse to where you want to save the file. For the file name, type "test.bat", and if your version of Windows has a "Save as type" option, choose "All files", otherwise it will save as a text file. Once all of this has been done click the Save button and exit notepad.
Now, to run the batch file, double-click or run the file like any other program. Once the batch file has completed running it will close the window automatically.
Batch commands
Just like all MS-DOS commands, all batch file commands are not case sensitive. However, in the below listing we have listed all commands in all caps to help you identify what is a command and what is not.
@
Does not echo back the text after that symbol. This most often used as @ECHO OFF to prevent any of the commands in the batch file from being displayed, just the information needed
%1
The percent followed by a numeric value, beginning with one, allows users to add variables within a batch file. The below line is an example of what can be used in a batch file.

ECHO Hello %1

When the above one-line batch file is created, add your name after the batch file. For example, typing myname (being the name of the bat file) and then your name:

myname bob
would output:

Hello bob Note: This can be extended to %2, %3, and so on.
::
One of two ways of adding remarks into the batch file without displaying or executing that line when the batch file is run. Unlike REM this line will not show regardless if ECHO off is in the batch file.
:LABLE
By adding a colon in front of a word, such as LABEL, you create a category, more commonly known as a label. This allows you to skip to certain sections of a batch file such as the end of the batch file. Also see GOTO.
CALL
This used to run another batch file within a batch file. When the batch file that is called is completed, the remainder of the original batch file is completed. Note if the batch file does not exist it will give an error message.
Choice
Allows for batch files and scripts to wait for the user to choose a set of choices
choice [/C[:]choices] [/N] [/S] [/T[:]c,nn] [text]
Options:
/C[:]choices         Specifies allowable keys. Default is YN
/N                       Do not display choices and ?at end of prompt string.
/S                       Treat choice keys as case sensitive.
/T[:]c,nn             Default choice to c after nn seconds
Text                    Prompt string to display
CLS
Just like the DOS command would clear your screen.
ECHO
Will echo a message in the batch file. Such as ECHO Hello World will print Hello World on the screen when executed. However, without @ECHO OFF at the beginning of the batch file you'll also get "ECHO Hello World" and "Hello World." Finally, if you'd just like to create a blank line, type ECHO. adding the period at the end creates an empty line.
EXIT
Exits out of the DOS window if the batch file is running from Windows.
GOTO
LABLE
Used to go to a certain label, such as LABEL. An example of GOTO would be to GOTO END.
Directs Windows to a labeled line in a batch program.
GOTO label
   Label---Specifies a text string used in the batch program as a label.
You type a label on a line by itself, beginning with a colon.
GOTO END
ECHO SKIPPING THIS
:END
ECHO DONE
IF
Used to check for a certain condition if the condition exists. If that condition exists it will perform that function.
PAUSE
Prompt the user to press any key to continue.
SHIFT
Changes the position of replaceable parameters in a batch program.
Changes the position of replaceable parameters in a batch file.
SHIFT [/n]
If Command Extensions are enabled the SHIFT command supports the /n switch that tells the command to start shifting at the nth argument, where n may be between zero and eight. For example:
SHIFT /2
would shift %3 to %2, %4 to %3, etc. and leave %0 and %1 unaffected.
Examples
The below example would be done in a batch file; in this example we are naming the batch file test.bat and it contains the below lines.
@ECHO OFF
ECHO - %1
SHIFT
ECHO - %1
After creating the above example test.bat file, if you were to type the below command at the MS-DOS prompt, it would print "- ONE" and then "- TWO"; this command is commonly used to work through each of the command extensions or remove command extensions.
TEST ONE TWO
START
Used for Windows 95Windows 98, and Windows NT 4.0 and above to start a windows application; such as  START C:\WINDOW\CALC would run the Windows Calculator. Users running Windows 3.x need to utilize the WIN command.  For example, WIN C:\Windows\CALC.EXE would run Windows and then Calculator after Windows has finished loading.
Syntax
Starts a separate window to run a specified program or command.
START ["title"] [/Dpath] [/I] [/MIN] [/MAX] [/SEPARATE | /SHARED]
[/LOW | /NORMAL | /HIGH | /REALTIME | /ABOVENORMAL | /BELOWNORMAL]
[/WAIT] [/B] [command/program]
[parameters]

"title"
Title to display in window title bar
path
Starting directory
/B
Start application without creating a new window. The application has ^C handling ignored. Unless the application enables ^C processing, ^Break is the only way to interrupt the application
/I
The new environment will be the original environment passed to the cmd.exe and not the current environment
/MIN
Start window minimized
/MAX
Start window maximized
/SEPARATE
Start 16-bit Windows program in separate memory space
/SHARED
Start 16-bit Windows program in shared memory space
/LOW
Start application in the IDLE priority class
/NORMAL
Start application in the NORMAL priority class
/HIGH
Start application in the HIGH priority class
/REALTIME
Start application in the REALTIME priority class
/ABOVENORMAL
Start application in the ABOVENORMAL priority class
/BELOWNORMAL
Start application in the BELOWNORMAL priority class
/WAIT
Start application and wait for it to terminate
command/program
f it is an internal cmd command or a batch file then the command processor is run with the /K switch to cmd.exe. This means that the window will remain after the command has been run.
If it is not an internal cmd command or batch file then it is a program and will run as either a windowed application or a console application.
parameters
These are the parameters passed to the command/program


If Command Extensions are enabled, external command invocation
through the command line or the START command changes as follows:
non-executable files may be invoked through their file association just by typing the name of the file as a command. (e.g. WORD.DOC would launch the application associated with the .DOC file extension). See the ASSOC and FType commands for how to create these associations from within a command script.
When executing an application that is a 32-bit GUI application, CMD.EXE does not wait for the application to terminate before returning to the command prompt. This new behavior does NOT occur if executing within a command script.
When executing a command line whose first token is the string "CMD " without an extension or path qualifier, then "CMD" is replaced with the value of the COMSPEC variable. This prevents picking up CMD.EXE from the current directory.
When executing a command line whose first token does NOT contain an extension, then CMD.EXE uses the value of the PATHEXT environment variable to determine what extensions to look for and in what order. The default value for the PATHEXT variable is:
.COM;.EXE;.BAT;.CMD
Notice the syntax is the same as the PATH variable, with semicolons separating the different elements.
When searching for an executable, if there is no match on any extension, then looks to see if the name matches a directory name. If it does, the START command launches the Explorer on that path. If done from the command line, it is the equivalent to doing a CD /D to that path.
Examples
start notepad myfile.txt
Start a new instance of notepad with the file myfile.txt open in it.  
start /MAX notepad
Start the notepad window with the screen maximized.
start /MIN mybatch.bat
The above example would start the batch file mybatch.bat in a minimized window.
start c:\music\"my song.mp3"
If the file or folder has a space in it you must surround it with quotes. In the above example we're starting the MP3 song file "my song.mp3". Without the quotes surrounding the file name with a space you would get a windows cannot find the file error.
start http://www.computerhope.com/
Open the Computer Hope web page from the command line.
Batch file examples
Running different programs
Below is an example of how you can implement the choice options into your batch files. Each line that is in red can be left out of the batch file. They have been included to help explain some of what the batch file means. Windows 2000 andWindows XP users will need to substitute the choice command with the set command; see the set command page for additional help and information with this command.
@ECHO OFF
REM - LABEL INDICATING THE BEGINNING OF THE DOCUMENT.
:BEGIN
CLS
REM - THE BELOW LINE GIVES THE USER 3 CHOICES (DEFINED AFTER /C:)
CHOICE /N /C:123 /M "PICK A NUMBER (1, 2, or 3)"%1
REM - THE NEXT THREE LINES ARE DIRECTING USER DEPENDING UPON INPUT
IF ERRORLEVEL ==3 GOTO THREE
IF ERRORLEVEL ==2 GOTO TWO
IF ERRORLEVEL ==1 GOTO ONE
GOTO END
:THREE
ECHO YOU HAVE PRESSED THREE
GOTO END
:TWO
ECHO YOU HAVE PRESSED TWO
GOTO END
:ONE
ECHO YOU HAVE PRESSED ONE
:END
How to start Windows files and other programs from a batch file
To run Microsoft Windows programs or files use the START command. The below example would run Windows Notepad.
START /MAX NOTEPAD
You can also specify the direct location of the file by typing the below command.
START /MAX C:\Windows\NOTEPAD.EXE
*Windows users who have a different directory (e.g. Windows 2000 users) would need to substitute WINNT or the name of their directory in place of Windows in the above example.
The /m representing it to start the window Maximized. See the start command page for additional information about this command.
Creating a batch file delay
Below is an example of how to delay a batch file anywhere from 5 to 99 seconds. In the below example we illustrate a 5 second delay.
Type NUL | CHOICE.COM /N /CY /TY,5 >NUL
Additionally, you could use the sleep file found on our utility download section.
How to make a time log in a batch file
The below example demonstrates how to create a time log of when the batch file is loaded, or for example, this could be used in the autoexec.bat when someone logs into a computer that supports this file.
ECHO. |TIME > TIME
COPY LOG +TIME
An alternate, slightly more complicated method that, to our knowledge, cannot be used in Windows NT, Windows 2000 or Windows ME would be the following:
echo @prompt set date=$d$_set time=$t$h$h$h > {a}.bat
%comspec% /e:2048 /c {a}.bat > {b}.bat
for %%v in ({b}.bat del) do call %%v {?}.bat
echo %date% %time% >> log
Another alternative is:
echo. |time |find "current" >> log
For the above batch file to work properly you must create a file called log, by typing edit log and then save and exit the file, creating a 0 bytes file. If this file is not created or not created properly you will receive the error message Content of destination lost before copy.
How to Create a DOS Batch File
   
Command Line Invocation
Running programs in a DOS Command Window straight from the command line has the limitation that you can only issue one command - you type the name of the program, then any control parameters and options, and then terminate the command line by pressing the Enter key at the end. This runs the program with the options you specified.
For example, NetMailBot is invoked directly on the command line ("C:\>") according to the following:
NetMailBot -to {To} -from {From} -subject {Subject} -server {Name of your SMTP Server} [Optional Parameters] (Enter)

Note that there is no newline (press of the Enter key) until the end; if the above example takes two physical lines on your screen, it's due to word wrap.

If you just want to use NetMailBot in simple situations, this might be acceptable. But if you use a lot of parameters and options, you don't want to have to type them all in each time you want to run NetMailBot. Also, if you have more complex situations, when the context of NetMailBot's use depends on other factors and decisions that have to be made "on the fly", then you need a "little program" that calls NetMailBot within the context of its own execution.
 Thus, you need a batch file!
What is a batch file?
Batch files are special files, often called scripts, that allow you to run programs from the DOS Command Window. Batch files are useful for storing sets of commands that are always executed together, in sequence, because you can simply enter the name of the batch file as the "command" instead of entering each command individually
In DOS, batch files end with a .BAT extension. The process of creating them is often called DOS batch scripting.
A Simple Example
Suppose the following text is saved in a file called "mybat.bat":
@ECHO ON
REM This is an example .BAT file output...
@ECHO OFF

REM Nothing fancy...
dir

This batch file contains two comments (or remarks, indicated by "REM") that just provide documentation for either the author or the user of the file. The first one is "echoed" to the screen because it is embedded inside two @ECHO commands that first turn on echoing and then turn it off. Everything between the @ECHO commands is displayed on the screen during the script's execution. After the second comment, there is a simple DOS "dir" command which, as usual, lists the contents of the current directory.

Note that the individual commands or comments are separated by newlines, that is, pressings of the Enter key.

Running the batch file executes the commands in "mybat.bat" sequentially.

Invoking the Batch File

A batch file can be run in two ways:

·         Straight from the command line
·         Double-clicking the file's icon in a Windows Explorer window (or via "My Computer")

For our example above, typing "mybat" or "mybat.bat" at the DOS command line yields the following output:



Double-clicking the batch file icon (see below) will open up a DOS Command Window, invoke NetMailBot within it according to the batch file, and then close the window when everything is done. Depending on how short your script is, if you blink, you might miss it!

A batch file icon:


@echo off
:LOOP
set cTime=%time:~0,-3%

if '%cTime%' equ '13:15' call "C:\Program Files\SI_SCOPE\close.bat"
if '%cTime%' equ '13:16' call "C:\Program Files\SI_SCOPE\copy.bat"
if '%cTime%' equ '13:17' call "C:\Program Files\SI_SCOPE\Hard Fault Captures\RenameFileToDate.bat"
if '%cTime%' equ '13:20' call "C:\WINDOWS\reboot.bat"

goto LOOP
if '%cTime%' equ '10:06' call Copy.bat
if '%cTime%' equ '10:07' call \Hard Fault Captures\RenameFileToDate.bat
if '%cTime%' equ '10:08' call C:\WINDOWS\reboot.bat
another program
CD \Program Files\SI_SCOPE\
set cTime=%time:~0,-3%

if '%cTime%' equ '10:06' call Copy.bat
if '%cTime%' equ '10:07' call \Hard Fault Captures\RenameFileToDate.bat
if '%cTime%' equ '10:08' call C:\WINDOWS\reboot.bat

pause
Advanced Windows batch example - conditional shutdown
@echo off
color 0E
title Conditional Shutdown.

:start
echo Welcome, %USERNAME%
echo What would you like to do?
echo.
echo 1. Shutdown in specified time
echo 2. Shutdown at a specified time
echo 3. Shutdown now
echo 4. Restart now
echo 5. Log off now
echo 6. Hibernate now
echo.
echo 0. Quit
echo.

set /p choice="Enter your choice: "
if "%choice%"=="1" goto shutdown
if "%choice%"=="2" goto shutdown-clock
if "%choice%"=="3" shutdown.exe -s -f
if "%choice%"=="4" shutdown.exe -r -f
if "%choice%"=="5" shutdown.exe -l -f
if "%choice%"=="6" shutdown.exe -h -f
if "%choice%"=="0" exit
echo Invalid choice: %choice%
echo.
pause
cls
goto start

:shutdown
cls
set /p min="Minutes until shutdown: "
set /a sec=60*%min%
shutdown.exe -s -f -t %sec%
echo Shutdown initiated at %time%
echo.
goto cancel

:shutdown-clock
echo.
echo the time format is HH:MM:SS (24 hour time)
echo example: 14:30:00 for 2:30 PM
echo.
set /p tmg=enter the time that you wish the computer to shutdown on:
schtasks.exe /create /sc ONCE /tn shutdown /st %tmg% /tr "shutdown.exe -s -t 00"
echo shutdown initiated at %tmg%
echo.

:cancel
set /p cancel="Type cancel to stop shutdown: "
if not "%cancel%"=="cancel" exit
shutdown.exe -a
cls
schtasks.exe /end /tn shutdown
cls
schtasks.exe /delete /tn shutdown
cls
echo Shutdown is cancelled.
echo.
pause
exit

Batch File Examples

Password Example

The following batch file can be used to establish a password for running a program. The batch file is named START.BAT and calls the program named CALC.EXE.
@ECHO OFF
IF %1==ExeScript GOTO OK
ECHO WRONG PASSWORD
GOTO END
:OK
ECHO PASSWORD IS ACCEPTED...STARTING
CALC.EXE
:END
Below you'll see the response of the computer to various commands.
First the bad password. At the prompt type START 123.
C:/>
C:/>START 123
C:/>BAD PASSWORD
Now use the correct password. Type the correct command at the prompt.
C:/>
C:/>START ExeScript
C:/>PASSWORD IS ACCEPTED...STARTING
At this point the CALC.EXE program starts.

Backup your .doc files (Windows NT/2000/XP version)

usage: backbat backupdir
where: backupdir is the directory to copy your .doc files
@echo off
if not "%1"=="" goto argsok
echo usage:  %0 backupdir
echo where: backupdir is the directory to copy your .doc files
goto end
 
:argsok
  setlocal
  set backupdir=%1
  if not exist %backupdir% goto notfile
  echo %backupdir% is a file
  goto end
:notfile
  rem  If the directory does not exist, create it.
  if exist %backupdir%\nul goto skipdir
  md %backupdir%
  if "%errorlevel%"=="0" goto skipdir
  echo Error creating backup directory
  goto end
:skipdir
  rem  Copy each .doc file one at a time.
  rem  Note:  the for loop variable (%%b) must be contain only one letter.
  for %%b in ( *.doc ) do copy %%b %backupdir% > nul
  rem  Use the for loop again to check if each file was copied (since it is
  rem  difficult to run multiple commands in a for loop).
  for %%b in ( *.doc ) do if not exist %backupdir%\%%b echo %%b was not copied
:end
rem  Clean up
endlocal

How to make a time log

In the following example, you can create a time log of when the batch file is loaded or, for example, in the autoexec.bat file when someone logs into a computer.
ECHO. |TIME > TIME
COPY LOG +TIME
An alternate slightly more complicated method that, to our knowledge, cannot be used in Windows NT, Windows 2000 or Windows ME would be the following:
echo @prompt set date=$d$_set time=$t$h$h$h > {a}.bat
%comspec% /e:2048 /c {a}.bat > {b}.bat
for %%v in ({b}.bat del) do call %%v {?}.bat
echo %date% %time% >> log
Another alternative is:
echo. |time |find "current" >> log
For the above batch file to work properly, you must create a file called log by typing "edit log" (without the quotes) and then save and exit the file which will create the file at 0 bytes. If this file is not created or not created properly, you will receive the error message, "Content of destination lost before copy".