Sunteți pe pagina 1din 10

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.

How to Use the Microsoft Batch File Language


Batch files are DOS command line commands Batched together. In Linux they are known as Shell
Scripts, and follow a completly different syntax. Early Windows users had to use a batch file
(autoexec.bat) to allocate a drive letter to their cd-roms, in order to install Windows from cd. Batch
files are not so crucial nowadays, although still supported by newer versions of Windows.
Under Windows XP/2000+, batch files (*.bat) run in a special window (aka Command Prompt)
created by c:\window\system32\cmd.exe (this could be called command.com in some instances).
Commands can be typed in individually, or listed sequentially in a batch file, requiring use of batch
file language. This How-To will tell you how to create and run a Microsoft batch file, giving a
simple backup as an example.

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.

Write the Batch File

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.

The Full Code

Practice your copy & pasting skills on the following text:

@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

Syntax Quick Guide

ECHO Prints to screen.


o examples:
@echo off (prevents each command being listed, only output is displayed)
echo Hello. (prints the word 'Hello.' Overrides @echo off.)
echo. (prints a blank line)
CLS Clears the screen, nice and neat.
MKDIR Creates a directory.
o example:
mkdir d:\backup (creates a directory on D called backup).
XCOPY Copies files and directories.
o examples:
xcopy c:\file.txt d:\file.txt (copies a named file from C drive to D).
xcopy c:\mydirectory d:\mydirectory /i (the '/i' switch insists that references
without a file extension are a directory).
xcopy c:\my documents\*.* d:\backup\my docments\ /s /i (the '/s' switch
copies all subdirectories).
CHOICE Captures a keyboard character (used for making menus).
o example:
choice /C:FN /N Select [F]ull Backup or [N]ew files only. (Lets the user
choose between options).
PAUSE Pauses the batch file, resumes on any keypress (except ctrl-z, which cancels).
o example:
echo You chose to backup NEW files. Hit a key to continue or ctrl-z to
cancel.
pause >nul
REM Comments out a line, so it is not executed.
o example:
REM format c: /u/q

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.

Things You'll Need

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.

How to Use the Command Prompt and Write


in Batch Languge
To start you are going to need to have two programs open. One of them is notepad. You can access
it by clicking Start > Run... > notepad. Minimize that and open the command prompt. You can
access that at Start > Run... > cmd.

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.

Echo this is a batch file


Echo I can tell the time
Echo tell the time
Time /t

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.

An Index of the Windows XP command line


(http://ss64.com/nt/)
a
ADDUSERS
ARP
ASSOC
ASSOCIAT
AT
ATTRIB
b
c

Add or list users to/from a CSV file


Address Resolution Protocol
Change file extension associations
One step file association
Schedule a command to run at a later time
Change file attributes

BOOTCFG Edit Windows boot settings


BROWSTAT Get domain, browser and PDC info
CACLS
CALL
CD
CHANGE
CHKDSK
CHKNTFS
CHOICE
CIPHER
CleanMgr
CLEARMEM
CLIP
CLS
CLUSTER
CMD
COLOR
COMP
COMPACT
COMPRESS
CON2PRT
CONVERT
COPY
CSCcmd
CSVDE

Change file permissions


Call one batch program from another
Change Directory - move to a specific Folder
Change Terminal Server Session properties
Check Disk - check and repair disk problems
Check the NTFS file system
Accept keyboard input to a batch file
Encrypt or Decrypt files/folders
Automated cleanup of Temp files, recycle bin
Clear memory leaks
Copy STDIN to the Windows clipboard.
Clear the screen
Windows Clustering
Start a new CMD shell
Change colors of the CMD window
Compare the contents of two files or sets of files
Compress files or folders on an NTFS partition
Compress individual files on an NTFS partition
Connect or disconnect a Printer
Convert a FAT drive to NTFS.
Copy one or more files to another location
Client-side caching (Offline Files)
Import or Export Active Directory data

DATE
DEFRAG
DEL
DELPROF
DELTREE
DevCon
DIR
DIRUSE
DISKCOMP
DISKCOPY
DISKPART

Display or set the date


Defragment hard drive
Delete one or more files
Delete NT user profiles
Delete a folder and all subfolders
Device Manager Command Line Utility
Display a list of files and folders
Display disk usage
Compare the contents of two floppy disks
Copy the contents of one floppy disk to another
Disk Administration

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

Display message on screen


End localisation of environment changes in a batch file
Delete one or more files
Quit the current script/routine and set an errorlevel
Uncompress files
Uncompress CAB files

FC
FIND
FINDSTR
FOR /F
FOR /F
FOR
FORFILES
FORMAT
FREEDISK
FSUTIL
FTP
FTYPE

Compare two files


Search for a text string in a file
Search for strings in files
Loop command: against a set of files
Loop command: against the results of another command
Loop command: all options Files, Directory, List
Batch process multiple files
Format a disk
Check free disk space (in bytes)
File and Volume utilities
File Transfer Protocol
Display or modify file types used in file extension associations

GLOBAL
GOTO

Display membership of global groups


Direct a batch program to jump to a labelled line

HELP

Online Help

iCACLS
IF
IFMEMBER
IPCONFIG

Change file and folder permissions


Conditionally perform a command
Is the current user in an NT Workgroup
Configure IP

KILL

Remove a program from memory

LABEL
LOCAL
LOGEVENT
LOGOFF
LOGTIME

Edit a disk label


Display membership of local groups
Write text to the NT event viewer.
Log a user off
Log the date and time in a file

MAPISEND
MBSAcli
MEM
MD
MKLINK
MODE
MORE
MOUNTVOL
MOVE
MOVEUSER
MSG
MSIEXEC
MSINFO
MSTSC
MUNGE
MV

Send email from the command line


Baseline Security Analyzer.
Display memory usage
Create new folders
Create a symbolic link (linkd)
Configure a system device
Display output, one screen at a time
Manage a volume mount point
Move files from one folder to another
Move a user from one domain to another
Send a message
Microsoft Windows Installer
Windows NT diagnostics
Terminal Server Connection (Remote Desktop Protocol)
Find and Replace text within file(s)
Copy in-use files

NET
NETDOM
NETSH
NETSVC
NBTSTAT
NETSTAT
NOW
NSLOOKUP
NTBACKUP
NTRIGHTS

Manage network resources


Domain Manager
Configure network protocols
Command-line Service Controller
Display networking statistics (NetBIOS over TCP/IP)
Display networking statistics (TCP/IP)
Display the current Date and Time
Name server lookup
Backup folders to tape
Edit user account rights

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

Search file(s) for lines that match a given pattern.

RASDIAL
RASPHONE
RECOVER
REG
REGEDIT
REGSVR32
REGINI
REM
REN
REPLACE
RD
RMTSHARE
ROBOCOPY
ROUTE
RUNAS
RUNDLL32

Manage RAS connections


Manage RAS connections
Recover a damaged file from a defective disk.
Registry: Read, Set, Export, Delete keys and values
Import or export registry settings
Register or unregister a DLL
Change Registry Permissions
Record comments (remarks) in a batch file
Rename a file or files
Replace or update one file with another
Delete folder(s)
Share a folder or a printer
Robust File and Folder Copy
Manipulate network routing tables
Execute a program under a different user account
Run a DLL command (add/remove print connections)

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

List running applications and services


Remove a running process from memory
Display or set the system time
Delay processing of a batch file
Set the window title for a CMD.EXE session
Task list with full path
Change file timestamps
Trace route to a remote host
Graphical display of folder structure
Display the contents of a text file

USRSTAT

List domain usernames and last login

VER
VERIFY
VOL

Display version information


Verify that files have been saved
Display a disk label

WHERE
WHOAMI
WINDIFF
WINMSD
WINMSDP
WMIC

Locate and display files in a directory tree


Output the current UserName and domain
Compare the contents of two files or sets of files
Windows system diagnostics
Windows system diagnostics II
WMI Commands

XCACLS
XCOPY
::

Change file and folder permissions


Copy files and folders
Comment / Remark

http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/ntcmds.mspx?
mfr=true

10

S-ar putea să vă placă și