How To Write A Batch File
How To Write A Batch File
Writing a batch file is used to automate daily and often mundane tasks. Instead of typing the same
commands day after day, you would simply double click the batch file to run said commands. These
instructions will show you how to do so.
Steps
1. Open up Notepad in Windows. You can do this by navigating to Start > Programs >
Accessories > Notepad, or simply by entering notepad under Start > Run.
2. Or open up notepad by C:\WINDOWS\system32\notepad.exe
3. Save your file before anything, so be sure to follow the instructions closely.
1. Go to File > Save As... and chose a file name.
2. Choose your desktop as the location to save, for now. Don't click Save just yet.
3. Click on the dropdown menu next to "File name". Select "All files" instead of Text
Document".
4. Add .bat to the end of your file name before you save. For example, you would type
example.bat.
5. Click on Save. If you did this correctly, you should see your file name in the title of
Windows Notepad. Make sure that it reads as example.batnot example.bat.txt.
Now you are ready to create your batch file.
4. Type "@echo off" on the first line of your batch file. This will prevent any spaces in the
batch file to be read by the program when executed.
5. Enter your commands. The following example below will show you how to create a batch
file that will automatically load wikiHow.com using Internet Explorer.
o
o
o
o
@echo off.
REM The following will open wikiHow.com in a new Internet Explorer window.
"start Iexplore.exe www.wikihow.com"
REM The following will open wikiHow.com in your default browser, but if it is IE
and you have another IE window open, then it will hijack that window.
o "start www.wikihow.com"
2. Save the file by going to "File>Save" and type in "wikihow.bat".
3. Run the file by double clicking the file on your desktop.
Tips
You can use third party editors such as UltraEdit to edit your batch file. But for the most
part, these are a waste of time when writing simple batch files.
Make sure not to enter any quotes used above. Those are simply to help distinguish the
command, filename, and file extension.
You will have to use quotes if you want to open a directory or file with spaces in its name,
like start "C:\Documents and Settings\"
You must click "Save as" and change ".txt" to "All files" in the file type drop-down menu.
Then, add ".bat" to your file name instead of ".txt".
When saving the batch file, type the filename as "filename.bat" without quotation marks,
and it's not necessary to select "All Files".
Batch files can also have a .cmd extension beginning with Windows 2000. There is no
difference in operation, but the .cmd files use 32-bit execution while the .bat files use 16-bit
execution.
Warnings
Depending on the commands you use, it can be dangerous. Be sure you know what you are
doing, and that none of the code is dangerous (e.g. batch commands to delete files).
Make sure you dont mess around too much with batch files because a simple command gone
wrong can cause very bad results.
Steps
Open your text editor. Expect to use keys A-Z/0-9/, the symbols (!$| etc), and Enter. Most
commands do not check entry for upper/lower case, so for the moment don't worry about CAPS (or
cApS). Each command (and it's parameters) goes on one line. Open a command line window
(cmd.exe) to test the commands you want to run. Arrange your windows so you can see them both.
This section does some hand-holding. If you want the finished script, jump to the next
section.
To start writing the file, most people start with <@echo off> as it stops each command being
printed as it is processed. It reduces clutter on the user's screen. To use this, type:
@echo off
Hit enter. Remember to press enter after each command. Let's welcome the user to our program.
Type:
echo Welcome to the Backup Script!
Did you hit enter again? Good. Now let's have a blank line (for neat spacing). Type:
echo.
And enter again, of course. Now let's do the real business. Type:
choice /C:FNQ /N Select [F]ull Backup or [N]ew files only. Press [Q] or [CTRL-Z] to exit.
2
That gives the user a choice. Either they press F, or N, or they press Q or CRTL-Z which cancels the
whole script. Now lets create commands for each choice. Type:
IF errorlevel 3 goto end
IF errorlevel 2 goto small_backup
IF errorlevel 1 goto full_backup
Now we're cooking! If the user presses Q the program returns a "3", and goes to section "end". If
they press N the program returns a "2", and goes to section "small_backup". If they press F, the
program returns a "1", and goes to "full_backup". "Errorlevel" is not a error message as such, just
the only way to set output from the CHOICE command.
Create those sections referred to above. Type:
:small_backup
echo.
echo.
echo You chose to backup NEW files. Hit any key to start or ctrl-z to cancel.
pause >nul
xcopy c:\mydirectory d:\mybackup /s/m/e
goto end
:full_backup
echo.
echo.
echo You chose to backup ALL files. Hit any key to start or ctrl-z to cancel.
pause >nul
xcopy c:\mydirectory d:\mybackup /s/e
goto end
:end
exit
Suggestion: Create the directories referred to above, and copy a few small test files into the source
directory ready for testing. Later you can change those directory names to suit your real <My
Documents>.
Well it's ready! In Notepad, save the file as <mybackup.bat>, and double click it.
@echo off
echo Welcome to the Backup Script!
echo.
choice /C:FN /N Select [F]ull Backup or [N]ew files Backup, or ctrl-z to exit.
IF errorlevel 3 goto end
IF errorlevel 2 goto small_backup
IF errorlevel 1 goto full_backup
:small_backup
echo.
echo.
echo You chose to backup NEW files. Hit any key to start or ctrl-z to exit.
pause >nul
xcopy c:\mydirectory d:\mybackup /s/m/e
goto end
:full_backup
echo.
echo.
echo You chose to backup ALL files. Hit any key to start or ctrl-z to exit.
pause >nul
xcopy c:\mydirectory d:\mybackup /s/e
goto end
:end
exit
Tips
Closing the Window: If you want the program to close when finished, leave the script as is.
If you would like to leave the window open for further commands, change the command
<exit> in the final section to <cmd>, which leaves the window open.
Current Directory: If the program references files in its own directory, you don't need to
put in the drive letter. So with the batch file in C:\ you can target files in c:\temp\ just by
typing: : Xcopy temp\*.* d:\temp /s/m
Warnings
While the commands shown here are pretty harmless, use of certain system commands in
batch files are potentially dangerous if misused.
The CHOICE command is not included in Windows XP Home nor Professional and will
cause the batch file to close abruptly without prior notice.
A text editor such as Notepad, or a programmer's editor such as HTML-Kit. Programs that
embed further information in files (like Word) are not suitable.
Access to a Command Prompt. Click <Start><Run>, and type "cmd". Or access the feature
under <Accessories> in the Start Menu.
Some files that you can do a test backup on. Try with a small directory with few files, until
you get going.
Steps
1. Know about these two pieces of software. Notepad isnt any text-editing program because
when you save it you can add any extension. Command prompt or CMD is like DOS but it
has loads more functionality. So at the command prompt to make things easier to use you
need to right click at the blue bar at the top and select properties. Under the tab options you
need to make sure QuickEdit Mode is enabled. Click OK. A box will appear to say if you
want to apply them or save them. Click on the box saying Save properties for future
windows with the same title. Click OK.
2. Learn about what it can do. You might think at this point that it is going to ruin my system.
It can if you have no idea what your doing. So to start, you need to know how to navigate
between directories. Type CD c:\ then hit enter. You will have noticed that you have gone
from your documents and settings directory to your C drive's root directory. If you follow
the following instructions, you are going to see every file and folder that is in that directory.
Type DIR and hit enter. Now you should see a long list. The rows of text in the last column
tells you the names of the directories branching from the root directory (the top) of your C
drive or in any other case, the directory you are currently in. If it is a folder, you will see
"<DIR>" in the column left of the name column in the same row. If it is as file it will not
have "<DIR>" next to it and will have a file extension (*.txt, *.exe, *.docx) at the end of the
name.
3. Make a directory to put all the batch files you are going to be making. Type MKDIR
mybatch. You just ordered windows to make a new directory or folder called mybatch. If
you want proof it is there type DIR again and look around. You should see it as a DIR.
4. Learn how to use the ping command. If you dont have Internet connection you can skip this
part but if you do you need to know it. Ping means to send packets of data around a website
and it to return back to you. If it does it means the website is working and is alive. So we are
5
5.
6.
7.
8.
going to test the well known website Google search engine so you are going to type PING
Google.com then hit enter. You should see something saying like Reply from 72.14.207.99:
bytes=32 time=117ms TTL=234. It might have this about four times. If it says that it cannot
ping your Internet connection isnt working or the website is dead. It will also say how
many packets it sent, received and lost. If it lost 0 the website is working 100%.
Opening a program from the windows directory and system32 is easy. Just type something
like mspaint.exe and it will open the paint program. It is harder to open a program within a
directory and you already did this using the user interface when you opened command
prompt and notepad earlier. The way to open a file or program from inside a directory is
harder. Assuming you still have notepad open type hello world. Then click file>save
as>helloworld.txt in mybatch folder in your c directory. Now reopen command prompt and
you will be in your documents and setting folder. Now type cd c:\mybatch hit enter and
then type helloworld.txt .You will not normally need to open command prompt again but it
makes it a little bit more challenging because you dont normally start in the C directory.
Make a DIR called deleteme in your c directory. To delete a directory you need to use the
RMDIR command. For example, 'RMDIR deleteme' basically means "delete the directory
named 'deleteme'". even though the command is RMDIR it will work with files as well as
sub-directories or folders. A little tip: when using the RMDIR command, navigate to the
directory that contains the file or sub-directory you would like to delete, and then type
'RMDIR *' with * being the name of the file or sub-directory you want to delete. navigate to
the C drive then type RMDIR deleteme. Then it will ask if you are sure you want to delete
the directory. Type Y for yes and then hit enter. You have just deleted the folder called
deleteme.
Rename a file or folder. You can use any of these two commands they are both exactly the
same, REN and RENAME so make a directory called idontlikemyname then type REN
idontlikemyname mynameisgood. You have just renamed the directory. Now you can
delete it.
Learn about batch programming and do it in notepad and not buy some 100 software for
something you can do for free. In notepad type:
9.
1. #@echo off
2.
3.
4.
5.
6.
1. You have just told it to echo three sentences. This is writing that will be shown on the
screen. @echo off means that you wont see on the screen the commands because if you did
it would say:
2.
1. Echo hello
Hello
1.
2. The command time /t tells you the time! You must put "/t" or it will want you to change the
time
3. Go to file>save as>(save it in your mybatch folder) called Timefirst.bat. Notice that is has
been saved as a bat file and not text. Dont get confused and called it Timefirst.batch
because it will not work.
6
Tips
There are other commands to the ones I told you so just type help to learn more.
Warnings
If you don't know what you are doing you can seriously mess up your machine.
DATE
DEFRAG
DEL
DELPROF
DELTREE
DevCon
DIR
DIRUSE
DISKCOMP
DISKCOPY
DISKPART
g
h
i
k
l
DNSSTAT
DOSKEY
DSADD
DSQUERY
DSMOD
DSRM
DNS Statistics
Edit command line, recall commands, and create macros
Add user (computer, group..) to active directory
List items in active directory
Modify user (computer, group..) in active directory
Remove items from Active Directory
ECHO
ENDLOCAL
ERASE
EXIT
EXPAND
EXTRACT
FC
FIND
FINDSTR
FOR /F
FOR /F
FOR
FORFILES
FORMAT
FREEDISK
FSUTIL
FTP
FTYPE
GLOBAL
GOTO
HELP
Online Help
iCACLS
IF
IFMEMBER
IPCONFIG
KILL
LABEL
LOCAL
LOGEVENT
LOGOFF
LOGTIME
MAPISEND
MBSAcli
MEM
MD
MKLINK
MODE
MORE
MOUNTVOL
MOVE
MOVEUSER
MSG
MSIEXEC
MSINFO
MSTSC
MUNGE
MV
NET
NETDOM
NETSH
NETSVC
NBTSTAT
NETSTAT
NOW
NSLOOKUP
NTBACKUP
NTRIGHTS
PATH
Display or set a search path for executable files
PATHPING Trace route plus network latency and packet loss
PAUSE
Suspend processing of a batch file and display a message
PERMS
Show permissions for a user
PERFMON Performance Monitor
PING
Test a network connection
POPD
Restore the previous value of the current directory saved by PUSHD
PORTQRY Display the status of ports and services
POWERCFG Configure power settings
PRINT
Print a text file
PRNCNFG Display, configure or rename a printer
PRNMNGR Add, delete, list printers set the default printer
PROMPT
Change the command prompt
PsExec
Execute process remotely
PsFile
Show files opened remotely
PsGetSid
Display the SID of a computer or a user
PsInfo
List information about a system
PsKill
Kill processes by name or process ID
PsList
List detailed information about processes
PsLoggedOn Who's logged on (locally or via resource sharing)
PsLogList Event log records
PsPasswd
Change account password
PsService View and control services
PsShutdown Shutdown or reboot a computer
PsSuspend Suspend processes
PUSHD
Save and then change the current directory
q
r
QGREP
RASDIAL
RASPHONE
RECOVER
REG
REGEDIT
REGSVR32
REGINI
REM
REN
REPLACE
RD
RMTSHARE
ROBOCOPY
ROUTE
RUNAS
RUNDLL32
SC
SCHTASKS
SCLIST
SET
SETLOCAL
Service Control
Create or Edit Scheduled Tasks
Display NT Services
Display, set, or remove environment variables
Control the visibility of environment variables
u
v
SETX
Set environment variables permanently
SHARE
List or edit a file share or print share
SHIFT
Shift the position of replaceable parameters in a batch file
SHORTCUT Create a windows shortcut (.LNK file)
SHOWGRPS List the NT Workgroups a user has joined
SHOWMBRS List the Users who are members of a Workgroup
SHUTDOWN Shutdown the computer
SLEEP
Wait for x seconds
SLMGR
Software Licensing Management (Vista/2008)
SOON
Schedule a command to run in the near future
SORT
Sort input
START
Start a program or command in a separate window
SU
Switch User
SUBINACL Edit file and folder Permissions, Ownership and Domain
SUBST
Associate a path with a drive letter
SYSTEMINFO List system configuration
TASKLIST
TASKKILL
TIME
TIMEOUT
TITLE
TLIST
TOUCH
TRACERT
TREE
TYPE
USRSTAT
VER
VERIFY
VOL
WHERE
WHOAMI
WINDIFF
WINMSD
WINMSDP
WMIC
XCACLS
XCOPY
::
http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/ntcmds.mspx?
mfr=true
10