-
Creating a batch script is as simple as writing a series of commands into a plain text file and saving it with the
.bator.cmdextension.-
Open a Text Editor:
- Use Notepad (built-in to Windows) or any code editor (like VS Code, Notepad++, etc.).
-
Write Commands:
@echo off echo Welcome to Batch Scripting! pause
-
Save the File:
-
File → Save As...
-
Choose “All Files” in the Save As type.
-
Name it like
example.bat(notexample.bat.txt). -
Choose ANSI or UTF-8 without BOM as encoding (optional but safer for special characters).
-
-
✅ Your script is ready to execute!
-
-
There are multiple ways to run a
.batfile:-
Double-click from File Explorer:
-
Just double-click the
.batfile, and it will open in a new Command Prompt window. -
It executes line-by-line and then closes (unless you use
pause).
-
-
Via Command Prompt:
-
Open CMD (
Win + R → type cmd → Enter). -
Navigate to the script location using
cdcommand. -
Run the script by typing:
example.bat
-
-
From Run Dialog:
-
Press
Win + R, then type:C:\Path\To\Your\Script.bat
-
Useful for launching tools quickly.
-
-
From Task Scheduler:
-
Useful for automation.
-
Create a scheduled task and point it to your batch file.
-
If the batch file doesn’t run or flashes and closes instantly, add a
pauseat the end to diagnose the output. -
Use
echostatements for debugging inside the script.
-
-
-
Batch scripting follows a line-by-line execution model. It doesn't require indentation or brackets like high-level languages, but there are some basic rules to keep in mind.
Rule Description One command per line Each line is a command executed in order Case-insensitive ECHO,echo, orEcHoare treated the sameComments Use REMor::to commentVariables Use %VAR_NAME%syntax for variablesExecution flow Use IF,GOTO, andFORfor logic and loopsEscape characters Use ^to escape special characters like&, `,>`
@echo off :: Suppresses command echoing echo Hello World :: Prints text pause :: Waits for a key press cls :: Clears the screen set VAR=value :: Creates a variable echo %VAR% :: Prints variable goto label :: Jumps to a label if EXIST file.txt echo Found file! :: Condition check
REM This is a comment :: This is also a comment (but safer to use REM in loops)
Batch scripts have characters that must be escaped or used with care:
Character Meaning >Output redirection <Input redirection ` ` Pipe &Command chaining ^Escape character To print these characters as text, escape them:
echo ^> This is not redirection
-
Always use
@echo offat the top to suppress command repetition. -
Use
pausefor debugging to see what’s happening. -
Always quote file paths with spaces:
"C:\Program Files\App\run.exe" -
Add comments to make scripts readable.
-
Use lowercase for readability, though it's not required.
-