Batch Exercises
Time to practise the whole course, including the system commands of the last section! Each exercise has a starter playground that runs as-is and prints a placeholder, so you can see the format. Replace the TODO part, press ▶ Run, and compare your output with the "Expected" lines. The exercises about tasklist, netstat, sc and reg work on saved command output (the playground has no live Windows system), just as your script would work on the live output with for /f ... in ('command'). Try for a few minutes before opening a solution.
| # | Exercise | Topics |
|---|---|---|
| 1 | PATH doctor | for, %PATH:;=" "%, delayed expansion |
| 2 | Memory per program | for /f tokens, string substitution, dynamic variable names |
| 3 | Listening ports | findstr, for /f tokens and delims, substrings |
| 4 | Required services | for /f, if ... else if, set "name_!var!=..." |
| 5 | Version check | registry output, for /f delims=., numeric comparison |
| 6 | Log level counter | findstr /c:, counting with for /f, tokens with * |
| 7 | Named arguments | call :label, shift, for /f delims=:, for /l |
| 8 | Numbered rename | dir /b /o:n, ren, zero padding |
| 9 | Backup rotation | counting, set /a, del |
| 10 | Ping summary | for /f, subroutines, padding |
1. PATH doctor
The variable P holds a messy PATH. Print every entry numbered, mark empty entries and duplicates (folders compare case-insensitively, so c:\tools repeats C:\Tools), then print a summary line.
Expected:
1. C:\Python313
2. C:\Tools
3. (empty)
4. c:\tools <-- duplicate
5. C:\Program Files\Git\cmd
6. C:\Python313\Scripts
7. C:\TOOLS <-- duplicate
entries: 7, duplicates: 2, empty: 1@echo off
setlocal enabledelayedexpansion
set "P=C:\Python313;C:\Tools;;c:\tools;C:\Program Files\Git\cmd;C:\Python313\Scripts;C:\TOOLS"
rem TODO: split P at ";" and check each entry
echo entries: 0, duplicates: 0, empty: 0entries: 0, duplicates: 0, empty: 0
Show solution
Replace everything after the data setup with:
set /a n=0, dup=0, empty=0
set "seen=;"
for %%p in ("%P:;=" "%") do (
set /a n+=1
set "dir=%%~p"
if "!dir!"=="" (
echo !n!. ^(empty^)
set /a empty+=1
) else (
set "test=!seen!"
call set "test=%%test:;!dir!;=%%"
if not "!test!"=="!seen!" (
echo !n!. !dir! ^<-- duplicate
set /a dup+=1
) else (
echo !n!. !dir!
set "seen=!seen!!dir!;"
)
)
)
echo entries: %n%, duplicates: %dup%, empty: %empty%Keeping a list seen of ;folder; strings and deleting the current folder from a copy of it is a duplicate test: if the copy changed, the folder was already there. %var:old=new% substitution ignores case, which is exactly what Windows paths need. call set adds the second expansion pass that lets !dir! appear inside a %...% substitution.
2. Memory per program
From the saved tasklist /fo csv /nh output, print for each program (name without .exe, in order of first appearance) how many processes it has and their total memory in MB (KB / 1024, rounded down).
Expected:
chrome: 3 processes, 546 MB
Code: 2 processes, 350 MB
svchost: 2 processes, 44 MB@echo off
setlocal enabledelayedexpansion
(
echo "chrome.exe","8812","Console","1","412,336 K"
echo "Code.exe","10716","Console","1","238,904 K"
echo "chrome.exe","9104","Console","1","96,480 K"
echo "svchost.exe","1120","Services","0","31,876 K"
echo "Code.exe","10802","Console","1","120,512 K"
echo "chrome.exe","9330","Console","1","51,204 K"
echo "svchost.exe","1288","Services","0","14,120 K"
) > procs.csv
rem TODO: sum the memory per program
echo chrome: 0 processes, 0 MBchrome: 0 processes, 0 MB
Show solution
Replace everything after the data setup with:
set "names="
for /f "tokens=1,5* delims=," %%a in (procs.csv) do (
set "mem=%%~b,%%~c"
set "mem=!mem:"=!"
set "mem=!mem:,=!"
set /a kb=!mem: K=!
if not defined total_%%~na set "names=!names! %%~na"
set /a total_%%~na+=kb, count_%%~na+=1
)
for %%n in (%names%) do (
set /a mb=total_%%n/1024
echo %%n: !count_%%n! processes, !mb! MB
)%%~na is the file name without extension, so the variables are called total_chrome, count_Code, … set /a creates them on first use. The names list remembers the order in which programs first appeared.
3. Listening ports
From the saved netstat -ano output, list every IPv4 port in LISTENING state with its PID, and say whether it is reachable from other machines (0.0.0.0) or only locally (127.0.0.1). Skip IPv6 lines (they start with [).
Expected:
port 135 PID 1032 (all interfaces)
port 445 PID 4 (all interfaces)
port 8080 PID 14220 (local only)
port 3389 PID 1240 (all interfaces)@echo off
setlocal enabledelayedexpansion
(
echo Proto Local Address Foreign Address State PID
echo TCP 0.0.0.0:135 0.0.0.0:0 LISTENING 1032
echo TCP 0.0.0.0:445 0.0.0.0:0 LISTENING 4
echo TCP 127.0.0.1:8080 0.0.0.0:0 LISTENING 14220
echo TCP 192.168.1.42:51234 140.82.112.4:443 ESTABLISHED 8812
echo TCP 0.0.0.0:3389 0.0.0.0:0 LISTENING 1240
echo TCP [::]:135 [::]:0 LISTENING 1032
echo UDP 0.0.0.0:5353 *:* 2480
) > netstat.txt
rem TODO: findstr LISTENING, then split the local address at ":"
echo port ? PID ? (?)port ? PID ? (?)
Show solution
Replace everything after the data setup with:
for /f "tokens=2,5" %%a in ('findstr /c:"LISTENING" netstat.txt') do (
set "addr=%%a"
if not "!addr:~0,1!"=="[" (
for /f "tokens=1,2 delims=:" %%x in ("%%a") do (
if "%%x"=="127.0.0.1" (set "scope=local only") else (set "scope=all interfaces")
echo port %%y PID %%b ^(!scope!^)
)
)
)Token 2 is the local address and token 5 the PID. A second for /f with delims=: splits 127.0.0.1:8080 into address and port. The IPv6 lines are skipped by looking at the first character; Windows' findstr /v could also filter them out.
4. Required services
The saved sc query output lists some services and their states. For each service in REQUIRED, print ok if it is running, its state if it isn't, or NOT INSTALLED if it is missing, then the number of problems.
Expected:
Dhcp: ok
sshd: STOPPED
Spooler: ok
WinDefend: NOT INSTALLED
2 problem(s)@echo off
setlocal enabledelayedexpansion
(
echo SERVICE_NAME: Spooler
echo STATE : 4 RUNNING
echo SERVICE_NAME: W32Time
echo STATE : 1 STOPPED
echo SERVICE_NAME: WSearch
echo STATE : 4 RUNNING
echo SERVICE_NAME: sshd
echo STATE : 1 STOPPED
echo SERVICE_NAME: Dhcp
echo STATE : 4 RUNNING
) > services.txt
set "REQUIRED=Dhcp sshd Spooler WinDefend"
rem TODO: remember each service state, then check REQUIRED
echo 0 problem(s)0 problem(s)
Show solution
Replace everything after the data setup with:
for /f "tokens=1,2,4" %%a in (services.txt) do (
if "%%a"=="SERVICE_NAME:" set "name=%%b"
if "%%a"=="STATE" set "state_!name!=%%c"
)
set /a problems=0
for %%s in (%REQUIRED%) do (
if not defined state_%%s (
echo %%s: NOT INSTALLED
set /a problems+=1
) else if not "!state_%%s!"=="RUNNING" (
echo %%s: !state_%%s!
set /a problems+=1
) else (
echo %%s: ok
)
)
echo %problems% problem(s)
exit /b %problems%The first loop turns the text into variables (state_Spooler=RUNNING, …); if not defined then detects missing services. Ending a real health-check script with exit /b %problems% lets a scheduled task record the problem count as its Last Result.
5. Version check
From saved reg query ... /s output with display names and versions, check the requirements Git 2.40, Python 3.12, Node.js 20.0 and Docker 27.0 (major.minor). Compare numbers, not strings: 3.9 is older than 3.12.
Expected:
Git: 2.47.1 ok
Python: 3.11.9 too old (need 3.12)
Node.js: 22.11.0 ok
Docker: missing (need 27.0)@echo off
setlocal enabledelayedexpansion
(
echo HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Git_is1
echo DisplayName REG_SZ Git
echo DisplayVersion REG_SZ 2.47.1
echo HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{B2C3D4E5}
echo DisplayName REG_SZ Python
echo DisplayVersion REG_SZ 3.11.9
echo HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{C3D4E5F6}
echo DisplayName REG_SZ Node.js
echo DisplayVersion REG_SZ 22.11.0
) > apps.txt
rem TODO: read DisplayName/DisplayVersion pairs, compare major*1000+minor
echo Git: ? okGit: ? ok
Show solution
Replace everything after the data setup with:
for /f "tokens=1,2,*" %%a in ('findstr /c:"REG_SZ" apps.txt') do (
if "%%a"=="DisplayName" set "app=%%c"
if "%%a"=="DisplayVersion" set "ver_!app!=%%c"
)
for %%r in (Git:2.40 Python:3.12 Node.js:20.0 Docker:27.0) do (
for /f "tokens=1,2 delims=:" %%n in ("%%r") do (
if not defined ver_%%n (
echo %%n: missing ^(need %%o^)
) else (
for /f "tokens=1,2 delims=." %%x in ("!ver_%%n!") do set /a have=%%x*1000+%%y
for /f "tokens=1,2 delims=." %%x in ("%%o") do set /a need=%%x*1000+%%y
if !have! GEQ !need! (echo %%n: !ver_%%n! ok) else (echo %%n: !ver_%%n! too old ^(need %%o^))
)
)
)Each DisplayVersion line belongs to the DisplayName line just before it. major*1000+minor turns a version into one comparable number (3.11 → 3011, 3.12 → 3012); comparing the strings "3.9" and "3.12" would give the wrong answer.
6. Log level counter
Count the INFO, WARN and ERROR lines of app.log, then list the time and message of each error.
Expected:
INFO: 4
WARN: 1
ERROR: 2
Errors:
08:03:40 database timeout after 30s
08:04:10 disk C: almost full@echo off
setlocal enabledelayedexpansion
(
echo 2026-10-17 08:00:01 INFO service started
echo 2026-10-17 08:00:05 WARN config file missing, using defaults
echo 2026-10-17 08:01:12 INFO user ada logged in
echo 2026-10-17 08:03:40 ERROR database timeout after 30s
echo 2026-10-17 08:03:41 INFO retrying
echo 2026-10-17 08:04:10 ERROR disk C: almost full
echo 2026-10-17 08:05:00 INFO backup done
) > app.log
rem TODO: count each level, then print the errors
echo INFO: 0INFO: 0
Show solution
Replace everything after the data setup with:
for %%l in (INFO WARN ERROR) do (
set /a n=0
for /f %%x in ('findstr /c:" %%l " app.log') do set /a n+=1
echo %%l: !n!
)
echo Errors:
for /f "tokens=2,3*" %%a in ('findstr /c:" ERROR " app.log') do echo %%a %%cSearching for " ERROR " with spaces avoids matching the word inside a message. In tokens=2,3* the * collects the rest of the line into the next letter, so %%c is the whole message (%%b is the level).
7. Named arguments
Write a subroutine :greet that accepts /name:<text> (default world), /count:<n> (default 1) and the flag /loud, in any order. It prints the greeting count times, as HELLO, NAME! when loud.
Expected:
HELLO, Ada!
HELLO, Ada!
---
Hello, world.@echo off
setlocal
call :greet /name:Ada /count:2 /loud
echo ---
call :greet /count:1
goto :eof
:greet
rem TODO: parse /name:, /count: and /loud, then greet
echo Hello, world.
exit /bHello, world.
---
Hello, world.
Show solution
The complete script:
:greet
setlocal
set "name=world"
set "count=1"
set "loud="
:parse
if "%~1"=="" goto run
for /f "tokens=1,* delims=:" %%k in ("%~1") do (
if /i "%%k"=="/name" set "name=%%l"
if /i "%%k"=="/count" set "count=%%l"
if /i "%%k"=="/loud" set "loud=1"
)
shift
goto parse
:run
for /l %%i in (1,1,%count%) do (
if defined loud (echo HELLO, %name%!) else (echo Hello, %name%.)
)
endlocal
exit /bThe :parse loop looks at %~1, splits it at the first : and then shifts until no arguments are left. setlocal at the top of the subroutine keeps its variables from leaking into the next call, which is why the second call sees the defaults again.
8. Numbered rename
Rename all .jpg files in photos (in name order, any case of extension) to photo_001.jpg, photo_002.jpg, … and leave other files alone.
Expected:
notes.txt
photo_001.jpg
photo_002.jpg
photo_003.jpg@echo off
setlocal enabledelayedexpansion
mkdir photos
cd photos
for %%f in (beach.jpg cat.JPG notes.txt sunset.jpg) do type nul > %%f
rem TODO: number the .jpg files with three digits
dir /b /o:nbeach.jpg
cat.JPG
notes.txt
sunset.jpg
Show solution
Replace everything after the data setup with:
set /a n=0
for /f "delims=" %%f in ('dir /b /o:n *.jpg') do (
set /a n+=1
set "num=00!n!"
ren "%%f" "photo_!num:~-3!.jpg"
)
dir /b /o:nPrepending zeros and keeping the last three characters (!num:~-3!) pads the counter. Reading the list from dir /b /o:n inside for /f captures it before renaming starts, so no file is processed twice.
9. Backup rotation
The backups folder holds one zip per day. Keep only the newest KEEP backups (the names sort by date) and delete the rest, printing each deleted name. Other files must not be touched.
Expected:
deleted backup-2026-10-01.zip
deleted backup-2026-10-02.zip
deleted backup-2026-10-03.zip
remaining:
backup-2026-10-04.zip
backup-2026-10-05.zip
backup-2026-10-06.zip
readme.txt@echo off
setlocal enabledelayedexpansion
mkdir backups
for %%d in (01 02 03 04 05 06) do type nul > backups\backup-2026-10-%%d.zip
type nul > backups\readme.txt
set KEEP=3
rem TODO: count the backups, delete the oldest total-KEEP
echo remaining:
dir /b /o:n backupsremaining:
backup-2026-10-01.zip
backup-2026-10-02.zip
backup-2026-10-03.zip
backup-2026-10-04.zip
backup-2026-10-05.zip
backup-2026-10-06.zip
readme.txt
Show solution
Replace everything after the data setup with:
set /a total=0
for /f %%f in ('dir /b /o:n backups\backup-*.zip') do set /a total+=1
set /a remove=total-KEEP
set /a i=0
for /f %%f in ('dir /b /o:n backups\backup-*.zip') do (
set /a i+=1
if !i! LEQ %remove% (
del "backups\%%f"
echo deleted %%f
)
)
echo remaining:
dir /b /o:n backupsISO dates (2026-10-01) sort alphabetically in date order, so the oldest files come first in dir /b /o:n. Two passes are needed: one to count, one to delete the first total-KEEP names.
10. Ping summary
The saved output of three ping -n 3 runs is in pings.txt. For each host print how many real replies (lines with bytes=) it got and UP (3/3), DOWN (0/3) or UNSTABLE. Remember that "Destination host unreachable" is not a real reply.
Expected:
192.168.1.1 3/3 UP
192.168.1.20 0/3 DOWN
203.0.113.10 2/3 UNSTABLE@echo off
setlocal enabledelayedexpansion
(
echo Pinging 192.168.1.1 with 32 bytes of data:
echo Reply from 192.168.1.1: bytes=32 time=2ms TTL=64
echo Reply from 192.168.1.1: bytes=32 time=1ms TTL=64
echo Reply from 192.168.1.1: bytes=32 time=3ms TTL=64
echo Pinging 192.168.1.20 with 32 bytes of data:
echo Reply from 192.168.1.42: Destination host unreachable.
echo Reply from 192.168.1.42: Destination host unreachable.
echo Request timed out.
echo Pinging 203.0.113.10 with 32 bytes of data:
echo Reply from 203.0.113.10: bytes=32 time=18ms TTL=56
echo Request timed out.
echo Reply from 203.0.113.10: bytes=32 time=21ms TTL=56
) > pings.txt
rem TODO: count real replies per host
echo 192.168.1.1 0/3 ?192.168.1.1 0/3 ?
Show solution
Replace everything after the data setup with:
set "host="
for /f "tokens=1,2,4" %%a in (pings.txt) do (
if "%%a"=="Pinging" (
if defined host call :report
set "host=%%b"
set /a ok=0
)
set "word=%%c"
if "%%a"=="Reply" if "!word:~0,6!"=="bytes=" set /a ok+=1
)
call :report
goto :eof
:report
set "line=%host% "
if %ok% EQU 3 (set "st=UP") else if %ok% EQU 0 (set "st=DOWN") else (set "st=UNSTABLE")
echo %line:~0,15% %ok%/3 %st%
exit /bEach Pinging line starts a new host, so the counter of the previous host is reported first. A :report subroutine avoids writing the output code twice (once per new host, once after the loop). Note that 192.168.1.20 got two "replies" from the local PC saying it is unreachable: still DOWN.
Learn more: for /f: Parse Text, setlocal & Delayed Expansion, call & Subroutines.
Test yourself
Why does a batch script compare versions as major*1000+minor instead of comparing the strings?
- String comparison is not allowed in if
- As strings, "3.9" sorts after "3.12", which is wrong for versions
- set /a can't hold decimals
- It is faster
Why is for /f %%f in ('dir /b /o:n *.jpg') safer than for %%f in (*.jpg) when the loop renames the files?
- dir is faster
- The list is captured completely before the loop body runs, so renamed files can't be picked up again
- for can't rename files
- dir /b includes hidden files