0% found this document useful (0 votes)
3 views16 pages

Batch Scripting Complete Guide

This document is a comprehensive study guide on Windows Batch Scripting, covering essential topics such as commands, control flow, variables, and real-world examples. It provides detailed explanations of batch file creation, execution methods, and various commands for file management, input/output operations, conditionals, loops, and error handling. Additionally, it includes practical examples and a quick reference cheatsheet for easy access to command syntax and usage.

Uploaded by

Arlane Ngounou
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views16 pages

Batch Scripting Complete Guide

This document is a comprehensive study guide on Windows Batch Scripting, covering essential topics such as commands, control flow, variables, and real-world examples. It provides detailed explanations of batch file creation, execution methods, and various commands for file management, input/output operations, conditionals, loops, and error handling. Additionally, it includes practical examples and a quick reference cheatsheet for easy access to command syntax and usage.

Uploaded by

Arlane Ngounou
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Windows Batch Scripting

Complete Study Guide


Commands · Control Flow · Scripting · Real-World Examples

1. Introduction to Batch — What is batch, .bat files, [Link]

2. Basic Commands — echo, cls, pause, rem, title, color

3. File System Commands — dir, cd, md, rd, copy, move, del, ren

4. Variables & Environment — set, %var%, %1-%9, environment vars


5. Input & Output — echo, set /p, redirection, pipes

6. Conditionals (IF) — if, if not, if exist, errorlevel

7. Loops (FOR) — for /l, for /f, for /r, for /d

8. GOTO & Labels — goto, :label, subroutines

9. Functions (CALL) — call :func, local scope, return values

10. String & Number Operations — set /a, string slicing, find, replace

11. Networking Commands — ping, ipconfig, netstat, net, nslookup

12. System & Process Commands — tasklist, taskkill, sc, reg, schtasks

13. Error Handling — errorlevel, exit /b, try patterns

14. Real-World Script Examples — Backup, log monitor, system info

15. Quick Reference Cheatsheet — All commands at a glance


1. Introduction to Batch Scripting
Batch scripting is Windows' built-in automation language. A batch file (with a .bat or .cmd extension) is a
plain text file containing a sequence of commands that are executed by the Windows Command Processor
([Link]). Batch scripts are widely used for system administration, automation, file management, and
network tasks.

Key Facts:
• File extensions: .bat (older, widely compatible) or .cmd (modern, recommended)
• Interpreter: [Link] — located at C:\Windows\System32\[Link]
• Case-insensitive: Commands and variable names are not case-sensitive
• No compilation needed: Scripts run directly — just double-click or run from command prompt
• Character encoding: ANSI by default; use chcp 65001 for UTF-8 support

Creating Your First Batch File:


@echo off REM This is my first batch file echo Hello, World! echo Today is: %date%
echo The time is: %time% pause

Save as [Link], then double-click it or run it from cmd. The @echo off at the top prevents each command from
being printed as it runs.

How to Run a Batch File:


Method How

Double-click Double-click the .bat file in Windows Explorer

Command Prompt Open [Link], navigate to folder, type: [Link]

Run dialog Press Win+R, type the full path to the .bat file

Task Scheduler Schedule via [Link] for automated runs

With arguments [Link] arg1 arg2 arg3


2. Basic Commands

Command Description

@echo off Suppress command echoing for the entire script

echo Hello Print 'Hello' to the screen

echo. Print a blank line (note the dot — no space)

echo %var% Print the value of a variable

cls Clear the screen

pause Stop and wait for any key press

pause >nul Pause silently (no 'Press any key' message)

rem This is a comment Add a comment — REM lines are ignored

:: This is a comment Alternative comment style (faster than REM)

title My Script Set the title of the command prompt window

color 0A Set window color: 0=black background, A=green text

color Reset color back to default

exit Close the command prompt window

exit /b Exit the script but keep the cmd window open

exit /b 0 Exit with error code 0 (success)

exit /b 1 Exit with error code 1 (failure)

Color Codes Reference:


Code Color Code Color

0 Black 8 Dark Gray

1 Dark Blue 9 Blue

2 Dark Green A Green

3 Dark Cyan B Cyan

4 Dark Red C Red

5 Dark Magenta D Magenta

6 Dark Yellow E Yellow

7 Gray F White

3. File System Commands

Command Description

dir List files and folders in current directory

dir /a List all files including hidden ones

dir /s List files in subdirectories recursively

dir /b Bare format — filenames only, no header

dir *.txt List only .txt files


cd folder Change to subfolder

cd .. Go up one directory level

cd /d D:\Projects Change drive and directory at once

cd %userprofile% Go to current user's home folder

md NewFolder Create a new directory (mkdir also works)

md A\B\C Create nested directories in one command

rd EmptyFolder Remove an empty directory

rd /s /q Folder Remove folder and all contents silently

copy [Link] dest\ Copy file to destination folder

copy *.txt C:\Backup\ Copy all .txt files to backup folder

xcopy src dst /s /e /i Copy folder tree including empty subfolders

robocopy src dst /e Robust copy — handles errors, mirrors folders

move [Link] C:\folder\ Move file to destination

del [Link] Delete a file

del /f [Link] Force delete read-only file

del /s /q *.tmp Delete all .tmp files in subdirs silently

ren [Link] [Link] Rename a file

attrib +h [Link] Hide a file

attrib -h [Link] Unhide a file

attrib +r [Link] Set file as read-only

type [Link] Display file contents in terminal

more [Link] Display file page by page

fc [Link] [Link] Compare two files and show differences


robocopy is more reliable than xcopy for large transfers — it retries on failure and supports mirror mode.
4. Variables & Environment
Variables in batch store text values. They are referenced with percent signs: %variablename%. Variable
names are case-insensitive.

Setting and Using Variables:


@echo off set name=Alice set age=25 set city=Paris echo Name: %name% echo Age:
%age% echo City: %city% :: Combining variables set greeting=Hello, %name%! You are
%age% years old. echo %greeting%

Command-Line Arguments:
When you call a script with arguments, they are available as %1, %2, %3... up to %9. %0 is the script
name itself.

@echo off :: Run as: [Link] Alice 30 Paris echo First argument: %1 echo Second
argument: %2 echo Third argument: %3 echo Script name: %0 echo All arguments: %* ::
Check if argument was provided if "%1"=="" ( echo ERROR: No argument provided! exit
/b 1 )

Built-in Environment Variables:


Variable Value / Description

%USERNAME% Current logged-in user name

%USERPROFILE% Path to user's home folder (C:\Users\Alice)

%COMPUTERNAME% Name of this computer

%OS% Operating system (Windows_NT)

%SYSTEMROOT% Windows installation directory (C:\Windows)

%SYSTEMDRIVE% Drive Windows is installed on (C:)

%TEMP% / %TMP% Path to temporary files folder

%PATH% Semicolon-separated list of executable search paths

%DATE% Current date (format depends on locale)

%TIME% Current time

%RANDOM% Random number between 0 and 32767

%ERRORLEVEL% Exit code of the last command (0=success)

%CD% Current working directory

%~dp0 Drive and path of the running batch file itself

%~nx0 Filename + extension of the running script


Tip: %~dp0 is extremely useful — it gives you the folder of the script itself, so your script works regardless of where
it is called from.
5. Input & Output

User Input with SET /P:


@echo off set /p username=Enter your name: set /p age=Enter your age: echo Hello
%username%, you are %age% years old! :: Confirm before deleting set /p confirm=Are
you sure? (Y/N): if /i "%confirm%"=="Y" ( echo Confirmed! ) else ( echo Cancelled. )

Redirection & Pipes:


Operator Meaning

cmd > file Redirect output to file (overwrite)

cmd >> file Redirect output to file (append)

cmd 2> file Redirect error output to file

cmd 2>&1 Redirect errors to same destination as normal output

cmd > nul Discard output (suppress it)

cmd 2>nul Suppress error messages

cmd1 | cmd2 Pipe output of cmd1 as input to cmd2

cmd < file Use file as input to command


@echo off :: Save dir listing to a file dir C:\Users > C:\Temp\[Link] :: Append
to a log file echo [%date% %time%] Script started >> C:\Temp\[Link] :: Suppress
all output some_command >nul 2>&1 :: Pipe examples dir | find ".txt" :: List only
.txt files netstat -an | findstr :80 :: Show connections on port 80 tasklist |
findstr chrome :: Find chrome processes
6. Conditionals — IF Statement
The IF statement lets your script make decisions. It compares values, checks file existence, and tests error
codes.

Basic IF Syntax:
@echo off set score=85 :: Basic comparison if %score% GEQ 90 echo Grade A :: IF with
block (parentheses) if %score% GEQ 75 ( echo Grade B echo Well done! ) else ( echo
Try harder ) :: IF / ELSE IF chain if %score% GEQ 90 ( echo A ) else if %score% GEQ
75 ( echo B ) else if %score% GEQ 60 ( echo C ) else ( echo F )

IF Comparison Operators:
Operator Meaning Example

EQU Equal to if %x% EQU 5

NEQ Not equal if %x% NEQ 0

LSS Less than if %x% LSS 10

LEQ Less or equal if %x% LEQ 100

GTR Greater than if %x% GTR 0

GEQ Greater or equal if %x% GEQ 1

== String equal if "%var%"=="hello"

/i Case-insensitive if /i "%var%"=="YES"

IF EXIST and ERRORLEVEL:


@echo off :: Check if a file exists if exist C:\Temp\[Link] ( echo File found! )
else ( echo File not found. ) :: Check if a folder exists if exist C:\Backup\ ( echo
Backup folder exists ) else ( md C:\Backup echo Backup folder created ) :: Check if
file does NOT exist if not exist [Link] echo No results yet :: Check error level
after a command ping [Link] -n 1 >nul 2>&1 if %errorlevel% EQU 0 ( echo Internet is
reachable ) else ( echo No internet connection! )
7. Loops — FOR Statement
The FOR command is the only looping construct in batch. It has several modes depending on what you
want to iterate over.

FOR /L — Count Loop (Numeric Range):


@echo off :: FOR /L %%var IN (start, step, end) for /l %%i in (1,1,5) do ( echo
Number: %%i ) :: Count down from 10 to 1 for /l %%i in (10,-1,1) do ( echo
Countdown: %%i ) :: Count in steps of 2 for /l %%i in (0,2,10) do echo %%i

FOR — Iterate Over a List:


@echo off :: Loop over a list of values for %%f in (apple banana cherry mango) do (
echo Fruit: %%f ) :: Loop over files in a folder for %%f in (C:\Logs\*.log) do (
echo Processing: %%f ) :: Loop over multiple file types for %%f in (*.txt *.csv
*.log) do echo %%f

FOR /R — Recursive File Loop:


@echo off :: Find all .txt files in all subdirectories for /r C:\Users %%f in
(*.txt) do ( echo Found: %%f ) :: Delete all .tmp files recursively for /r . %%f in
(*.tmp) do ( del "%%f" echo Deleted: %%f )

FOR /D — Directory Loop:


@echo off :: Loop over all subfolders in a directory for /d %%d in (C:\Users\*) do (
echo Folder: %%d )

FOR /F — Read File or Command Output:


@echo off :: Read lines from a text file for /f "delims=" %%l in ([Link]) do (
echo Line: %%l ) :: Parse command output for /f "tokens=*" %%l in ('dir /b *.txt')
do ( echo File: %%l ) :: Read CSV with delimiter for /f "tokens=1,2,3 delims=," %%a
in ([Link]) do ( echo Name=%%a Age=%%b City=%%c ) :: Get current IP address for /f
"tokens=2 delims=:" %%i in ('ipconfig ^| findstr IPv4') do ( set ip=%%i ) echo My
IP: %ip%

Inside FOR loops use %%variable (double %). In command prompt (interactive) use %variable (single %).
8. GOTO & Labels
GOTO jumps execution to a label — a line starting with a colon. It is used for branching, menus, and early
exit.

@echo off set /p choice=Enter 1, 2 or 3: if "%choice%"=="1" goto option1 if


"%choice%"=="2" goto option2 if "%choice%"=="3" goto option3 goto invalid :option1
echo You chose Option 1 goto end :option2 echo You chose Option 2 goto end :option3
echo You chose Option 3 goto end :invalid echo Invalid choice! :end echo Done. pause

Interactive Menu Example:


@echo off :menu cls echo ========================================== echo SYSTEM
MANAGEMENT MENU echo ========================================== echo 1. Show System
Info echo 2. List Running Processes echo 3. Show Network Info echo 4. Exit echo
========================================== set /p opt=Select an option: if
"%opt%"=="1" goto sysinfo if "%opt%"=="2" goto procs if "%opt%"=="3" goto netinfo
if "%opt%"=="4" goto quit echo Invalid option & pause & goto menu :sysinfo
systeminfo | more pause & goto menu :procs tasklist pause & goto menu :netinfo
ipconfig /all pause & goto menu :quit echo Goodbye! exit /b 0
9. Functions with CALL
Batch functions use CALL :label to jump to a subroutine and return with EXIT /B. Use
SETLOCAL/ENDLOCAL to keep variables local.

@echo off setlocal :: Call functions call :greet Alice call :greet Bob call :add 10
20 echo Sum result: %result% call :log "Script finished" exit /b 0 :: ■■ FUNCTIONS
BELOW ■■■■■■■■■■■■■■■■■■ :greet echo Hello, %~1! exit /b 0 :add set /a
result=%~1 + %~2 exit /b 0 :log echo [%date% %time%] %~1 >> [Link] exit /b 0

Always put functions after EXIT /B at the end of the script so they are not executed accidentally on first run.

10. String & Number Operations

Arithmetic with SET /A:


@echo off set /a x=10 set /a y=3 set /a sum = x + y set /a diff = x - y set /a
product = x * y set /a quotient = x / y set /a remainder = x %% y set /a power = x *
x echo Sum: %sum% echo Diff: %diff% echo Product: %product% echo Quotient:
%quotient% echo Remainder: %remainder% :: Increment / Decrement set /a counter=0
set /a counter+=1 set /a counter-=1 :: Random number 1-100 set /a rand=(%random% %%
100) + 1 echo Random: %rand%

String Operations:
@echo off set str=Hello World Batch :: String length (via trick) :: Substring:
%var:~start,length% echo First 5 chars: %str:~0,5% echo From pos 6: %str:~6% echo
Last 5 chars: %str:~-5% echo Skip last 6: %str:~0,-6% :: Replace substring set
replaced=%str:World=Everyone% echo Replaced: %replaced% :: Convert to uppercase
(via cmd trick) for /f "usebackq delims=" %%i in (`echo %str%`) do set upper=%%i ::
Check if string contains substring echo %str% | findstr /i "World" >nul if
%errorlevel%==0 echo String contains 'World'
11. Networking Commands
Windows batch has access to powerful built-in networking commands for diagnostics, configuration, and
administration.

11.1 Diagnostics & Connectivity


Command Description

ping hostname Test connectivity — sends 4 ICMP packets by default

ping -t hostname Ping continuously until Ctrl+C

ping -n 10 hostname Send exactly 10 ping packets

ping -l 1000 hostname Ping with 1000-byte packet size

tracert hostname Trace route to destination — show each hop

pathping hostname Combined ping + tracert with statistics

nslookup domain Resolve domain name to IP address

nslookup -type=MX domain Look up mail server records

curl -I url Fetch HTTP headers (Windows 10+)

curl -O url Download a file from URL

wget url Download file (if wget is installed)

11.2 Interface & Configuration


Command Description

ipconfig Show basic IP addresses for all adapters

ipconfig /all Detailed info including MAC, DNS, DHCP

ipconfig /release Release DHCP IP address

ipconfig /renew Request new DHCP IP address

ipconfig /flushdns Clear the DNS resolver cache

ipconfig /displaydns Show cached DNS entries

arp -a Show ARP cache — IP to MAC mapping table

arp -d * Clear entire ARP cache

route print Display full routing table

Add
route add [Link] MASK [Link] GWa default gateway route

netsh wlan show profiles List saved Wi-Fi network profiles

Show
netsh wlan show profile name=X Wi-Fi password for profile X
key=clear

Show all network interfaces


netsh interface show interface

Disablestate
netsh advfirewall set allprofiles Windows
offFirewall (admin)

11.3 Connections & Ports


Command Description

netstat -an Show all active connections and listening ports


netstat -b Show executable behind each connection (admin)

netstat -o Show Process ID (PID) for each connection

netstat -r Show routing table

netstat -s Show statistics per protocol

netstat -an | findstr :80 Filter connections on port 80

11.4 Network Shares & Users (NET Commands)


Command Description

net view List computers visible on the network

net view \\PC-NAME List shares on a specific computer

net use Z: \\server\share Map network share to drive letter Z

net use Z: /delete Disconnect mapped drive Z

net user List all local user accounts

net user username /add Create a new local user account

net user username /delete Delete a local user account

net localgroup administratorsAdd user to Admins


username /add group

net start ServiceName Start a Windows service

net stop ServiceName Stop a Windows service

net share List current network shares on this machine


12. System & Process Commands

Command Description

tasklist List all running processes

Filter processes by name


tasklist /fi "imagename eq [Link]"

tasklist /svc Show services hosted in each process

taskkill /im [Link] Kill all Notepad processes

taskkill /pid 1234 Kill process by PID

taskkill /im [Link] /f Force kill a process

start [Link] Open Notepad in new window

start /wait [Link] Run and wait for it to finish

start /min [Link] Start cmd minimized

schtasks /create /tn Name /trSchedule


[Link]
/sctask
daily /st 08:00

schtasks /run /tn Name Run scheduled task immediately

schtasks /delete /tn Name /f Delete a scheduled task

schtasks /query List all scheduled tasks

sc query List all Windows services

sc query ServiceName Check status of a service

sc start ServiceName Start a service

sc stop ServiceName Stop a service

sc config SvcName start= autoSet service to start automatically

reg query HKLM\... Query Windows registry key

Add/modify registry value


reg add HKCU\... /v name /d val

reg delete HKCU\... /v name Delete a registry value

systeminfo Display detailed system information

wmic cpu get name Show CPU model name

wmic memorychip get capacity Show RAM capacity

wmic os get caption Show Windows edition

shutdown /r /t 60 Restart in 60 seconds

shutdown /s /t 0 Shut down immediately

shutdown /a Abort a pending shutdown


13. Error Handling
@echo off setlocal :: ■■ Basic error checking after each command ■■ copy
[Link] [Link] if %errorlevel% NEQ 0 ( echo ERROR: Copy failed with code
%errorlevel% exit /b 1 ) echo Copy succeeded. :: ■■ Short form using conditional
execution ■■ copy [Link] [Link] && echo OK || echo FAILED :: && runs next
command only if previous succeeded :: || runs next command only if previous FAILED
:: ■■ Centralized error handler ■■ call :do_copy [Link] [Link] call
:do_copy [Link] [Link] echo All done! exit /b 0 :do_copy copy "%~1" "%~2"
>nul 2>&1 if %errorlevel% NEQ 0 ( call :log "ERROR copying %~1 to %~2" exit /b 1 )
call :log "Copied %~1 to %~2 successfully" exit /b 0 :log echo [%date% %time%] %~1
echo [%date% %time%] %~1 >> [Link] exit /b 0

Use && and || for concise error handling on a single line. Use centralized :log functions for consistent logging in
larger scripts.
14. Real-World Script Examples

Example 1 — Automated Backup Script:


@echo off setlocal :: Configuration set SOURCE=C:\Users\%USERNAME%\Documents set
DEST=D:\Backups set LOG=%DEST%\[Link] set
DATE_TAG=%date:~-4%-%date:~3,2%-%date:~0,2% :: Create destination if needed if not
exist "%DEST%" md "%DEST%" echo [%date% %time%] Backup started >> "%LOG%" echo
Backing up %SOURCE%... robocopy "%SOURCE%" "%DEST%\%DATE_TAG%" /e /r:3 /w:5
/log+:"%LOG%" if %errorlevel% LEQ 1 ( echo Backup completed successfully! echo
[%date% %time%] Backup OK >> "%LOG%" ) else ( echo ERROR: Backup failed! Check %LOG%
echo [%date% %time%] Backup FAILED >> "%LOG%" ) exit /b 0

Example 2 — System Information Report:


@echo off setlocal set REPORT=%TEMP%\[Link] echo
===================================== > "%REPORT%" echo SYSTEM REPORT - %date%
%time% >> "%REPORT%" echo ===================================== >> "%REPORT%" echo.
>> "%REPORT%" echo [COMPUTER] >> "%REPORT%" echo Computer: %COMPUTERNAME% >>
"%REPORT%" echo User: %USERNAME% >> "%REPORT%" echo OS: %OS% >> "%REPORT%" echo. >>
"%REPORT%" echo [NETWORK] >> "%REPORT%" ipconfig | findstr "IPv4" >> "%REPORT%"
echo. >> "%REPORT%" echo [DISK USAGE] >> "%REPORT%" wmic logicaldisk get
caption,size,freespace >> "%REPORT%" echo. >> "%REPORT%" echo [TOP PROCESSES] >>
"%REPORT%" tasklist /fo csv /nh | sort >> "%REPORT%" type "%REPORT%" echo. echo
Report saved to: %REPORT% pause

Example 3 — Batch File Renamer:


@echo off setlocal enabledelayedexpansion set /p folder=Enter folder path: set /p
ext=File extension to rename (e.g. txt): set /p prefix=New prefix: set counter=1
for %%f in ("%folder%\*.%ext%") do ( set newname=%prefix%_!counter!.%ext% ren "%%f"
"!newname!" echo Renamed: %%~nxf -> !newname! set /a counter+=1 ) echo. echo Done!
Renamed %counter% files. pause

enabledelayedexpansion allows variables (using !var!) to be updated inside FOR loops and IF blocks.
15. Quick Reference Cheatsheet
Category Key Commands / Syntax

Script Start @echo off | setlocal | setlocal enabledelayedexpansion

Output echo text | echo. (blank line) | cls | pause

Comments REM comment | :: comment

Variables set name=val | %name% | set /p name=Prompt: | set /a math

Arguments %0=script %1-%9=args %*=all args %~dp0=script folder

Built-in Vars %USERNAME% %DATE% %TIME% %CD% %RANDOM% %ERRORLEVEL%

File System dir /b | cd /d | md | rd /s /q | copy | robocopy

File Operations del /f /q | ren | move | attrib +h | type | fc

IF Conditions if EQU/NEQ/GTR/LSS | if exist | if not | if /i (nocase)

FOR Loops for /l %%i in (1,1,10) | for %%f in (*.txt) | for /f | for /r

GOTO goto :label | :label | goto :eof

Functions call :func arg1 | exit /b 0 | %~1 (safe arg expand)

Error Handling %errorlevel% | cmd && echo OK || echo FAIL | exit /b 1

Redirection > overwrite | >> append | 2>nul | >nul 2>&1 | | pipe

Networking ping | tracert | ipconfig /all | netstat -an | nslookup

NET Commands net user | net use | net start/stop | net view

Processes tasklist | taskkill /im | start /wait | schtasks

Services sc query | sc start/stop | net start/stop

System Info systeminfo | wmic cpu get name | wmic os get caption

Practice tip: Open [Link] and try commands one by one. Create small .bat files to automate tasks you do often —
file cleanup, backups, or system checks.

You might also like