Batch files (.bat or .cmd) are plain-text scripts interpreted by cmd.exe. Each line represents a distinct DOS command. These scripts allow for system automation without complex compilation. Case sensitivity is generally ignored in commands, but filenames usually retain their original casing.
System Variables
Environment variables provide access to critical paths and configurations:
%~dp0: Directory of the executing script (d=drive,p=path).%SystemRoot%: TypicallyC:\WINDOWS.%ProgramFiles%: Standard installation directory.%TEMP%: Temporary storage location.%Path%: Search path for executables.
Example usage for navigation:
cd /d "%~dp0"
set "SCRIPT_ROOT=%cd%"
This ensures subsequent commands run relative to where the script resides.
Arguments and Parameters
Runtime arguments are passed as strings separated by spaces or tabs. Access them via indices:
%0: The script filename itself.%1to%9: Sequential parameters passed after the script name.
Sample invocation:
automation.bat argA argB
Inside automation.bat:
echo First parameter is %1
echo Second parameter is %2
echo Running file is %0
Control Flow Commands
Batch scripts lack traditional functions but support flow control logic.
Goto and Labels
Use labels (e.g., :START) to redirect execution flow. Combine with if for conditional branching.
:start
if exist backup.zip goto verify
exit /b 1
:verify
echo Verification complete
If Conditional Statements
Check conditions before executing commands:
- File Existence:
if exist config.ini edit config.ini - String Comparison:
if "%VAR%"=="YES" echo Match - Return Codes:
if errorlevel 5 goto high_error. Note: Error levels must be checked from highest to lowest. - Negation:
if not defined PATH ...
For Looping
Iterate through sets of items:
:: Iterate over files
for %%f in (*.log) do @echo %%f
:: Numeric loop (1 to 5)
for /L %%i in (1,1,5) do echo %%i
:: Recursive directory scan
for /R . %%d in (*) do echo %%d
In batch scripts within files, double percent signs (%%) are required instead of single % used in command lines.
Command Reference
Echo and Output Control
Disable output display to suppress clutter:
@echo off
echo This text appears
rem Use :: for comments
echo Hidden messages > C:\temp\log.txt
The @ symbol hides the current command line from the console.
Process Management
Terminate processes by image name:
taskkill /f /im chrome.exe
Wait for completion using the wait switch:
start /wait app.exe
Launch minimized:
start /min update_installer.exe
String Manipulation
Batch scripting lacks native string functions, but substring extraction works via modification syntax.
set var=2023-10-05
set short_date=%var:~0,10%
echo Short Date: %short_date%
:: Replacing characters
set str=abc123
echo %str:1=kk%
:: Output: abckk23
Delayed Expansion
Variable expansion normally occurs when a line is parsed, not executed. To update variables in side loops, enable delayed expansion:
setlocal enabledelayedexpansion
set count=0
for /l %%i in (1,2,5) do (
set /a count=!count!+1
echo Count is !count!
)
endlocal
Note the use of ! exclamation marks.
File and Registry Operations
Deletion and Removal
Force delete directories and files silently:
del /q /s d:\logs\*.txt
rmdir /s /q d:\old_temp
Use quotes if paths contain spaces.
Registry Editing
Modify values using built-in registry tools:
reg add "HKLM\Software\MyApp" /v Version /t REG_SZ /d "2.0" /f
reg delete "HKCU\TempKey" /f
Export a key to a .reg file for backup:
reg export "HKLM\SYSTEM\CurrentControlSet\Services" backup.reg
Common keys include Run for startup applications and Environment for system-wide variables.
Service Control
Manage system services directly:
net start Spooler
sc config Spooler start=demand
net stop wuauserv
Environment Variable Modification
Update PATH or custom variables permanently:
setx JAVA_HOME "C:\Java\jdk-17"
setx Path "%JAVA_HOME%;%PATH%"
To apply changes immediately without reboot, restart the explorer process:
taskkill /f /im explorer.exe
start explorer.exe
Network Diagnostics
Verify connectivity and ports:
:: Continuous ping
ing -t target_ip
:: Scan local subnet
for /L %%i in (1,1,254) do (
ping -n 1 192.168.0.%%i >nul && echo %%i is online
)
Check listening ports using netstat -ano.
Practical Scripts
Secure Launch Example
Prompt user for password before proceeding:
@echo off
set "PASS=admin"
setlocal enabledelayedexpansion
for /l %%n in (1,1,3) do (
set /p inp=Enter Password:
if "!inp!"=="%PASS%" (
goto execute
) else (
echo Wrong password. Attempt %%n of 3.
)
)
shutdown /l
exit
:execute
echo Access Granted
pause
Automated Setup
Create a setup script that validates prerequisites:
@echo off
set "BIN_DIR=C:\MyApp\bin"
set "LOG_FILE=C:\setup.log"
echo Start Setup > %LOG_FILE%
if not exist "%BIN_DIR%" mkdir "%BIN_DIR%"
xcopy "%~dp0files" "%BIN_DIR%" /E /I /Y >> %LOG_FILE%
type %LOG_FILE%
pause
Best Practices
- Always escape quotes in paths containing spaces.
- Test error handling using
if errorlevel. Redirect standard output/error to log files using> log.txt 2>&1. - Use ANSI encoding for compatibility on older systems; UTF-8 may cause display issues with special characters in legacy consoles.
- Keep scripts modular using
callto invoke sub-routines without terminating the main parenet script.
Common Return Codes
Understanding exit codes aids debugging:
0: Success1: General failureErrorLevel > 1: Specific failures depending on the command (e.g., xcopy, format).
Refer to command_name /? in the terminal for specific command documentation.