Renaming and Moving Files
Quick renames and relocations — batch excels at bulk operations here.
REN / RENAME (same command)
Bulk rename with FOR loop (super common)
More advanced bulk:
MOVE (rename + relocate, or just move)
Note: MOVE can't cross drives for folders, use ROBOCOPY or XCOPY + DEL for that.
Bulk move example:
PowerShell bonus for bulk magic:
But again — these CMD versions are perfect for lightweight .bat scripts.
Quick summary table (screenshot-friendly)
Copying Files
Copying is where things get interesting, from simple single-file moves to full folder mirrors with retries.
COPY: basic, fast, good for single files or quick combines
Pros: Simple, built-in everywhere
Cons: No subfolders by default, no resume on fail, no attribute copy
XCOPY — the old advanced copy (still works great in 2025+)
Common switches:
/S = copy subdirectories (except empty)
/E = include empty subdirs
/H = copy hidden & system files
/C = continue on errors
/I = assume destination is folder if copying multiple files
/Y = no overwrite prompt
/R = overwrite read-only
/D:m-d-y = only copy newer files
Still useful for legacy scripts, but…
ROBOCOPY: the modern king (built-in since Vista, unbeatable in 2026)
Killer features:
/MIR = mirror (copy + delete extras in destination — dangerous!)
/E = subdirs including empty
/COPY:DATSOU = data, attributes, timestamps, owner, auditing, security
/R:3 /W:5 = retry 3 times, wait 5 sec
/MT:16 = multi-threaded (faster!)
/Z = restartable (great for networks)
/LOG:file or /TEE = logging
Quick safe backup example:
Pro tip: ROBOCOPY is usually what you want instead of COPY/XCOPY in new scripts.
FILE ATTRIBUTES
Files have flags like read-only, hidden, etc. — ATTRIB lets you view and change them.
Basic usage:
Common attributes:
R = Read-only
H = Hidden
S = System
A = Archive (used for backups)
Extra modern ones (NTFS):
I = Not content indexed
L = Reparse point / symbolic link
Bulk examples:
/S = subfolders
/D = include directories too
PowerShell nicer alternative:
But ATTRIB is perfect for quick batch tweaks.
DIRECTORY OPERATIONS
All the folder-level basics — still rock-solid.
MKDIR / MD — create folders (auto-creates parents)
RMDIR / RD — remove empty folders (or everything with /S)
CD / CHDIR — change current directory
DIR — list contents (tons of options)
Popular combo for clean recursive list:
Quick cheat-sheet table (screenshot gold) - Directory & Attribute Operations
TOPIC 5: SUBSTRING EXTRACTION
Batch uses this syntax to pull parts of a string variable:
start = position to begin (0 = first character)
length = how many chars to take (omit = to the end)
Negative numbers count from the right (super useful!)
Quick examples (assume these at the top of your script):
Real-world use case — parse date
Pro tips
Always quote variables with spaces: set "var=hello world"
Use %%~nxF in FOR loops for built-in parsing (name + extension)
Watch regional date/time formats — %DATE% and %TIME% vary by locale!
String Replacement
Replace parts of a string with this syntax:
Replaces all occurrences by default
To remove → leave new empty: %var:old=%
Case-sensitive!
Examples
Trick: Replace only first occurrence (no native way — use delayed expansion + clever loop)
Better modern alternative - For serious string work, many people switch to PowerShell inside batch:
But pure batch is great for quick stuff — and these tricks are battle-tested.
Quick reference table (screenshot heaven)
STRING LENGTH
Batch has no built-in %var length% — so we improvise!
Method 1: Loop through characters (most reliable pure-batch way)
Why 12? It's a safe starting point (most strings are shorter). You can start higher (e.g. 1024) if needed — just make sure it's larger than any possible string.
Method 2: FINDSTR regex trick (clever & fast for medium strings)
More popular one-liner version (no temp file):
Method 3: External helpers (cleanest for serious work)
PowerShell is usually the winner when you need exact length (especially with Unicode/emojis).
CONCATENATION
This one is straightforward — batch loves gluing strings.
Simple concatenation
Building in loops (very common for logs, paths, CSV lines)
Or building a comma-separated list:
Pro tip: Always use !var! inside blocks with EnableDelayedExpansion — or you'll get old values.
CASE CONVERSION
Again — no built-in upper/lower in batch. Workarounds only.
Method 1: PowerShell (easiest & best)
Method 2: Manual lookup table (pure batch, no external tools)
This is slow and ugly for long strings — use only when you can't call PowerShell.
TRIMMING WHITESPACE
Batch trimming is loop-based — no trim() function.
Leading spaces (remove from start)
Trailing spaces (remove from end)
Combined trim (both sides)
Faster one-liner tricks (sometimes used)
→ Works for leading/trailing, but not multiple internal spaces.
PowerShell clean version:
Summary:
READING USER INPUT
The star here is SET /P — it pauses and waits for the user to type something.
Example — simple name greeting:
Input validation (non-empty, numeric, etc.)
More advanced validation (e.g. yes/no):
Pro tip 2026-style For real menus or choices, many people now use CHOICE (built-in) instead of SET /P for yes/no/single-key input — faster & cleaner:
But SET /P is still king for free-text input.
DISPLAYING OUTPUT
Make your script look nice and user-friendly.
ECHO — your main output tool
@echo off at top hides commands
ECHO. = empty line
ECHO is on. fix: ECHO. or @ECHO OFF
COLOR — change console text/background (fun for branding!)
Common combos:
0A = matrix green
4E = red bg + yellow text (warning)
2F = green bg + white (success)
TITLE — set the window title (makes it professional)
CLS — clear the screen (clean start or between steps)
Full pretty script snippet:
REDIRECTION
Redirect input/output/errors instead of showing everything on screen.
Output redirection (> overwrites, >> appends)
Input redirection (< feeds file to command)
Error redirection (2> sends errors to file)
Combined (most common — capture everything)
Or separate logs:
Summary:
PIPING
The pipe () takes the output of one command and feeds it directly as input to the next, chaining is super powerful for filtering, searching, sorting, etc.
Real examples
1. Find all .txt files in dir listing
2. See only Chrome processes
3. Count lines in a log file
4. Sort a directory by size (descending)
5. Chain more — find errors and count them
Pro tip - Pipes work great with MORE, SORT, FIND, FINDSTR, CLIP (copy to clipboard), etc.
Modern upgrade: PowerShell pipes objects (not just text) → much more powerful:
But in pure batch, is your best friend for quick filters.
SUPPRESSING OUTPUT
You don't always want text flooding the screen — especially in background scripts or when running silently.
Redirect to NUL (the black hole — discards output)
Suppress errors only
Suppress everything (normal + errors)
Pro tip: In scripts, put @echo off at the top + these redirections to make everything feel clean and professional.
ANSI ESCAPE CODES (COLOR/FORMATTING)
Since Windows 10 (build 1511+) and especially Windows 11, ANSI escape sequences work natively in CMD, PowerShell, and Windows Terminal — no extra hacks needed!
Enabling ANSI (usually already on in modern Windows Terminal — but you can force it)
(Or just use Windows Terminal — it's enabled by default.)
Basic color codes (format: ESC [ code m)
Color Examples
Common codes quick-ref
Cursor & positioning (fun for progress bars or menus)
Simple progress bar example (ANSI + loop)
Notes for 2026
Works best in Windows Terminal (Win + X → Terminal)
CMD.exe supports ANSI but looks better with Consolas font + transparency
PowerShell 7+ handles ANSI beautifully too
Quick ANSI cheat-sheet
DEFINING FUNCTIONS (LABELS AS FUNCTIONS)
Batch functions are labels (starting with :) that you treat like subs — define them at the bottom of your script for readability.
Basic syntax (put after main code)
Invoking with CALL
Why use them? Reuse code without copy-paste — e.g. a logger function called multiple times.
Full script example:
Pro tip: Always end with GOTO :EOF — it "returns" control.
Without it, execution falls through to the next label (messy!).
PASSING PARAMETERS
Pass args like command-line params — access as %1, %2, etc. inside the function.
Basic passing & using
SHIFT — move args left (e.g. process variable number of params)
Access all params at once (%*)
Tips
%~1 = remove quotes around arg (safer with spaces)
Up to 9 args easy (%1–%9); use SHIFT for more
In loops: Use !1! with delayed expansion if needed
Returning Values
No true returns — use tricks like ERRORLEVEL or vars.
Via ERRORLEVEL (for codes, like 0=success)
Via environment variables (most flexible for strings/numbers)
ENDLOCAL workaround (return across scope boundaries — see 7.4)
endlocal & set = sneaky way to "export" vars
LOCAL VS GLOBAL SCOPE
By default, vars are global — changes in functions affect everywhere (risky!).
SETLOCAL — create local scope inside function
ENDLOCAL — exits scope (vars revert)
Returning across SETLOCAL (tricks needed since locals vanish)
Method 1: endlocal & set "var=%local_var%" (as above)
Method 2: Pass back via param (hacky: for /f %%r in ('echo %local_var%') do endlocal & set "result=%%r")
Always use setlocal EnableDelayedExpansion for !vars! inside locals
Scope table (screenshot gold)
RECURSIVE FUNCTIONS
Batch supports recursion (function calls itself) — but watch stack depth (limited to ~512 levels or crashes!).
Basic syntax (needs base case to stop!)
Use case: Tree traversal (e.g. recursive dir list)
Base case — always check (e.g. IF %depth% GTR 10 GOTO :EOF) to avoid infinite loops/stack overflow.
Pro tips 2026
Recursion is slow/risky in batch — prefer FOR /R for trees
PowerShell: Real recursion with functions (way safer/deeper)
Batch has no try/catch, no exceptions, no stack traces — just ERRORLEVEL and your own discipline. But with the patterns below, you can make scripts that fail gracefully, log problems, and keep going (or exit cleanly) instead of just crashing silently or spewing garbage.
UNDERSTANDING ERRORLEVEL
ERRORLEVEL is a hidden number every command sets when it finishes — basically the “exit code”.
0 = success (almost everything good returns 0)
anything else = some kind of failure
Common values (not universal — depends on the command)
How to check it (two main styles — both still work in 2026)
Quick test script
ERROR CHECKING PATTERNS
Best practice: Check after every command that can fail (especially COPY, MOVE, DEL, ROBOCOPY, NET USE, etc.).
Pattern 1: Immediate check
(ROBOCOPY returns 0–3 = mostly okay, 8+ = real errors)
Pattern 2: Conditional chaining (&& = run next only if previous succeeded, || = only if failed)
Pattern 3: Log errors
TRY-CATCH EQUIVALENT (WORKAROUND)
No native try/catch — so we fake it with check → branch.
Classic pattern
Even cleaner with a :handle_error label
GRACEFUL DEGRADATION & USER-FRIENDLY MESSAGES
Ideas to make scripts nicer when things go wrong
1. Fallbacks
2. Friendly messages
3. Clean exit (close files, reset state)
LOGGING
Logging turns silent failures into debuggable ones.
Basic timestamped log
Separate info vs error logs
Quick logging table (screenshot-ready)
PING (Connectivity Testing)
Basic reachability check, still the fastest way to see if something is alive.
Useful options
Simple “is host up?” check in batch
Pro tip 2026 PowerShell: Test-Connection -Count 1 -Quiet google.com → returns true/false directly.
IPCONFIG (IP CONFIGURATION)
View and manage your network adapters.
Most common uses
Quick reset script
NETSTAT (NETWORK STATISTICS)
See what’s connected/listening (though netstat is deprecated in favor of netstat -an still works, but PowerShell is cleaner now).
Classic views
Find process using a port
2026 note
Get-NetTCPConnection in PowerShell is way better:
NET COMMANDS
The Swiss Army knife of Windows networking & user management.
NET USE — map/unmap drives
NET USER — local users
NET START / STOP — services
Interactive mode (type commands after nslookup)
Tracert(Traceroute)
See the path packets take — great for finding slow hops.
2026 alternative Test-NetConnection -TraceRoute google.com (PowerShell) — nicer output.
ARP (Address Resolution Protocol)
View/manipulate IP ↔ MAC cache (useful for LAN troubleshooting).
Use case — detect ARP spoofing or map local network.
CURL / CERTUTIL (Downloading Files)
CURL — native since Windows 10 1803 (~2018)
CERTUTIL — fallback (works everywhere, even old Windows)
PowerShell (cleanest modern way)
FTP Automation
Old-school but still alive for legacy servers.
Interactive mode (manual)
Non-interactive (scripted) — create ftp_commands.txt
Then run:
2026 reality FTP is insecure, prefer SFTP (WinSCP scripting), PowerShell WinSCP .NET assembly, or just curl sftp://...
Quick network commands table
MODULE 10: SYSTEM ADMINISTRATION (Part 1)
Task Scheduling (SCHTASKS)
schtasks is the command-line interface for Windows Task Scheduler — create, delete, query, change tasks.
Create a task (most common pattern)
Common switches:
/TN = task name
/TR = program/script to run
/SC = schedule (MINUTE, HOURLY, DAILY, WEEKLY, MONTHLY, ONCE, ONLOGON, ONIDLE)
/ST = start time (HH:MM)
/RU = run as user (SYSTEM = highest privilege, no password needed)
/RL HIGHEST = run with highest privileges
/F = force (overwrite if exists)
/MO = modifier (e.g. /MO 15 for every 15 minutes)
Delete task
Query tasks
Modify existing task (e.g. change time)
Quick one-liner to create a reboot reminder every Monday at 9 AM:
SERVICE MANAGEMENT
Two main tools: SC (more powerful) and NET START/STOP (simpler).
SC command (Service Control)
NET START / STOP (easier for quick actions)
Practical script — restart service if stopped
REGISTRY OPERATIONS (REG)
reg is the command-line Registry editor — query, add, delete, export/import.
Query
Add key/value
Delete
Export / Import (backup & restore)
Use cases in batch
Add startup programs (Run key)
Disable features (e.g. telemetry keys)
Persistence for scripts
Forensics / auditing (export keys before changes)
PROCESS MANAGEMENT
TASKLIST — list processes
TASKKILL — kill by name or PID
WMIC — advanced queries (still useful, though deprecated-ish)
System Information
SYSTEMINFO — quick system overview
WMIC queries — detailed hardware/software
Parsing example — extract OS version
DISK OPERATIONS
These commands deal directly with storage — be extremely careful. One wrong parameter can wipe data permanently.
DISKPART — the low-level disk partitioning tool (very dangerous!)
Used for: creating/deleting partitions, assigning letters, cleaning disks, converting to GPT/MBR
Always run as Administrator
Never use /clean without triple-checking — it wipes the entire disk!
Basic safe examples
Non-interactive script example (assign letter safely)
Warning 2026: Use PowerShell’s Get-Disk, New-Partition, Format-Volume instead — much safer and scriptable.
CHKDSK — check & repair file system errors
Common pattern — schedule repair on next boot
FORMAT — format a drive (erases everything!)
Warning: Never run on C: or system drive unless you mean to destroy Windows.
VOL — show volume label & serial
Quick one-liner to list all drive labels:
USER AND GROUP MANAGEMENT
These NET commands manage local users and groups (not domain/Active Directory — for that use PowerShell AD module or RSAT tools).
NET USER — manage local user accounts
NET LOCALGROUP — manage local groups
Practical examples
Create standard user + add to Users group
List all users and their groups (simple script)
2026 modern alternative PowerShell is far better for user/group management:
ARRAYS (PSEUDO-ARRAYS)
Batch has no real arrays, but we fake them with numbered variable names (arr[0], arr[1], …).
Creating a pseudo-array
Looping through the array
Practical example — store & display drive letters
2026 tip If you need real arrays → just use PowerShell inside batch (see 11.3). Pure batch arrays are slow and limited to ~9999 elements max.
PARSING JSON/XML
Batch has zero native JSON or XML parsing — so we hack it or call helpers.
Method 1: Crude FOR /F + FINDSTR (only simple cases)
Very fragile — breaks on nested objects, escaped quotes, etc.
Method 2: Call PowerShell (clean & powerful)
Method 3: External tools (jq for JSON, xmlstarlet or xq for XML)
Download jq.exe (single file, portable) → place in script folder or PATH.
Same for XML with xml.exe or xq (jq for XML).
Recommendation 2026 If JSON/XML parsing is more than 2–3 lines → call PowerShell or use jq. Pure batch parsing is maintenance hell.
INTERACTING WITH POWERSHELL
This is the killer feature of modern batch: treat PowerShell as your high-level function library.
Basic call
Pass variables from batch → PowerShell
Capture PowerShell output into batch variable
Real hybrid example — get free disk space
Full hybrid script tip Start with @echo off & powershell -NoExit -Command "& { . .\myscript.ps1 }" if you want to mix batch + PS more deeply.
DATE AND TIME MANIPULATION
%DATE% and %TIME% are locale-dependent — formats vary (Kenya usually DD/MM/YYYY).
Extract parts (example: DD/MM/YYYY HH:MM:SS)
Standardize to YYYY-MM-DD
Date arithmetic (add/subtract days — hacky but works)
Format current date/time any way
OBFUSCATION TECHNIQUES
Obfuscation in batch is about making code harder to read/understand/flag, mostly for CTF challenges, proof-of-concept evasion demos, or protecting intellectual property in legacy scripts.
Variable indirection (using variables to build other variable names)
More evil version (common in CTF):
Encoding commands (Base64, ROT13)
Most common: Base64-encode payload → decode at runtime with certutil or powershell.
PowerShell one-liner Base64 execute (very common):
(That decodes to echo "Hello from Nairobi!")
ROT13 (simple Caesar cipher) — less common but still seen:
String concatenation obfuscation
Break commands across variables + concatenation:
Or worse (CTF style):
Use cases (educational / CTF only)
CTF reverse-engineering challenges
Demonstrating how weak signature-based AV can be bypassed (for training/red-team awareness)
Protecting sensitive strings in legacy deployment scripts (very limited effectiveness today)
Modern AV/EDR looks at behavior, not just strings, so obfuscation mostly delays detection by seconds.
SELF-EXTRACTING SCRIPTS
Idea: embed files (exe, zip, ps1, etc.) inside the batch file → extract & run at runtime.
Most common method: Base64 encode payload → embed as multi-line string → decode with certutil.
Step-by-step example (small text file embedded)
1. Encode your payload once:
2. Copy content of secret.b64 into your batch as variable (use multi-line set)
More compact trick — use here-document style (less readable)
Creating portable installers
Common pattern:
Embed installer.exe as base64
Decode to %TEMP%
Run with silent flags
Clean up
2026 reality check
AV heavily flags certutil -decode patterns now
Better modern alternatives: self-extracting ZIP (7z sfx), PowerShell -EncodedCommand, or real installers (Inno Setup, NSIS)
GUI Elements (Basic)
Batch is console-only, but we can fake GUI popups using MSHTA, VBS, or PowerShell.
MSHTA (HTML Application) — popup windows
More beautiful message box:
VBScript integration (MsgBox / InputBox)
InputBox example
PowerShell GUI (Windows Forms) — most powerful
What’s next in your practice phase?
Maybe WMI deep dive, COM objects, HTA apps, or security considerations?
Or want to build a real advanced project (e.g. self-extracting portable tool, obfuscated config loader, GUI launcher with PowerShell forms, or CTF-style challenge solver)?
PART 3: REAL-WORLD PROJECTS MODULE 12: AUTOMATION PROJECTS
This is where everything we've covered comes together. Each project is a practical, reusable script you can adapt for your own machine, work, or even share with friends/family in Nairobi.
I'll give you:
A clear goal for each project
Main techniques used (linking back to previous modules)
A complete, well-commented starter script (copy-paste ready)
Customization ideas & next steps
All scripts include error handling, logging, user-friendly messages, and modern touches (2026 Windows 11 compatible).
System Backup Script
Goal: Automatically back up important folders (Documents, Desktop, Pictures) to external drive or network share, with optional compression, incremental logic, and scheduling.
Techniques used:
ROBOCOPY (robust copy)
FOR /R (recursive file handling)
Date/time formatting
SCHTASKS (scheduling)
Logging & error checking
Starter script — DailyBackup.bat
To schedule daily at 2 AM (run once as admin):
Log File Analyzer
Goal: Scan log files (e.g. error.log, access.log) for errors/warnings, count them, and create a daily summary.
Techniques:
FOR /F (line-by-line parsing)
FINDSTR (search keywords)
Pseudo-arrays (store counts)
Redirection & logging
Starter script — LogAnalyzer.bat
Automated Software Installer
Goal: Download & silently install a list of programs if not already present.
Techniques:
Registry check (REG QUERY)
CURL / CERTUTIL download
Silent install flags
Pseudo-array for program list
Starter script (example: Chrome + VLC + 7-Zip)
Network Monitoring Script
Goal: Ping hosts + check websites/services, log status, alert on failure.
Techniques:
PING + ERRORLEVEL
CURL for HTTP check
Logging with timestamp
Optional sound alert (PowerShell)
Starter script
File Organizer
Goal: Sort Downloads folder by file type into subfolders, handle duplicates.
Techniques:
FOR /R + MOVE
Pseudo-array for extensions
Dry-run mode
String manipulation (extension extraction)
Starter script — OrganizeDownloads.bat
There you go — five solid, practical projects to start with.
Next steps:
Pick one project that solves a real problem for you (e.g. backup or Downloads organizer)
Customize it (change paths, add features, improve error handling)
Schedule it with SCHTASKS
Run it → break it → fix it → repeat
Automation Projects with a strong set of practical, real-life batch scripts. These are the kinds of tools people actually run on their machines — either manually or scheduled — to save time and reduce mistakes.
Each project includes:
Goal & main techniques
A clean, commented starter script
Quick ways to extend / schedule it
All scripts are ready to copy-paste and customize.
Batch File Menu System
Goal: Create an interactive menu that loops until the user chooses to exit — the foundation for many admin dashboards.
Techniques: CHOICE, SET /P, :labels as functions, GOTO loop
Starter script — AdminMenu.bat
To make it autorun: Put shortcut in Startup folder or schedule with SCHTASKS /SC ONLOGON.
Git Automation Script
Goal: Safe daily commit & push to GitHub (or self-hosted Git) — great for notes, configs, scripts.
Techniques: Check if git exists, ERRORLEVEL, logging, date in commit message
Starter script — GitDailyBackup.bat
Disk Cleanup Automation
Goal: Safe weekly cleanup of temp files, recycle bin, basic browser cache.
Techniques: DEL / RD / FOR /F, PowerShell for Recycle Bin
Starter script — WeeklyCleanup.bat
User Account Management
Goal: Bulk-create local users from CSV, set passwords, add to groups, generate report.
CSV format (users.csv):
Starter script — BulkUsers.bat
Run as admin — add error checking for existing users.
Scheduled Maintenance Script
Goal: One master script that runs backup + cleanup + git push + network check — scheduled nightly.
Starter script — NightlyMaintenance.bat
Final Chapter Advice: Leveling Up After the Notes
1. The 80/20 Rule of Batch Mastery
You already know 80% of what most people ever need.
The remaining 20% that makes someone “really good” at batch is:
Writing small, focused scripts that solve one real problem for yourself.
You don’t read continuously, you apply what you have read, mix concepts, try out things till they work.
Make short and long batch files. Start small and when you advance, try automate, adding GUIs and everything else.
Reading other people’s .bat files (GitHub, forums, old sysadmin toolkits)
Debugging ugly real-world scripts someone else wrote 10 years ago
Knowing when NOT to use batch (and switching to PowerShell early)
2. Your Personal Practice Roadmap (Next 30–90 Days)
Copy this checklist into your notes and tick things off:
Sandboxes:
Sandboxie
Shade Sandbox
VMWare
VirtualBox
Hyper-V
Windows Sandbox
Or rent a cloud virtual machine😂
If you don’t care, you will just one day point a batch file to the wrong directory, I swear! 😈
Have a nice time scripting, superstar!❤
🟢🟢🟢🟢🟢🟢🟢🟢🟢🟢🟢🔴🔴🔴🔴🔴🔴🔴🔴🔴🔴🔴
From here, you don’t need notes, you need to practice.
As we head to the final chapter in commandline, I'll show you alot of things, malware analysis and reverse engineering applications. Let's go!😤
And I think all these chapters were covered back in commandline2.pdf @RennexTech Github
Ethical Hacking & Malware Analysis (RedTeam/Security) 😎
MODULE 13: Reconnaissance
13.1 Network Enumeration
Discover active hosts (ping sweep)
Port scanning (basic, no nmap equivalent in pure batch)
ARP scanning (identify devices on local network)
DNS enumeration (zone transfer attempts)
13.2 System Enumeration
OS version (SYSTEMINFO)
Installed software (WMIC, registry queries)
Running processes (TASKLIST)
Logged-in users (QUERY USER, NET SESSION)
Network configuration (IPCONFIG, ROUTE PRINT)
13.3 User Enumeration
List local users (NET USER)
List domain users (NET USER /DOMAIN)
Group membership (NET LOCALGROUP)
Recently accessed files (recent folder, registry)
13.4 Credential Harvesting
Stored credentials (CMDKEY /LIST)
Browser passwords (external tools, NirSoft)
Wi-Fi passwords (NETSH WLAN SHOW PROFILES, NETSH WLAN SHOW PROFILE name KEY=CLEAR)
Registry-stored credentials
13.5 File Searching
Search for sensitive files (passwords.txt, config files)
Recursive directory search (FOR /R + FINDSTR)
Keyword-based search (passwords, credentials, API keys)
MODULE 14: Persistence
14.1 Registry Run Keys
Add to startup (HKCU\Software\Microsoft\Windows\CurrentVersion\Run)
System-wide startup (HKLM version)
Using REG ADD command
14.2 Scheduled Tasks
Create task that runs at logon (SCHTASKS /CREATE)
Hidden tasks (remove from Task Scheduler GUI)
14.3 Startup Folder
Copy script to Startup folder (%APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup)
14.4 Service Creation
Create Windows service (SC CREATE)
Auto-start service
Disguising as legitimate service (naming)
14.5 DLL Hijacking (Batch as Dropper)
Batch script drops malicious DLL
Places in application directory
Application loads DLL on next run
14.6 WMI Event Subscriptions
Create WMI event filter (triggers on event)
Execute batch script via WMI
Stealthy persistence (hard to detect)
MODULE 15: Privilege Escalation
15.1 UAC Bypass Techniques
Fodhelper.exe method (registry hijacking)
Eventvwr.exe method (registry hijacking)
Sdclt.exe method
Disclaimer: Educational purposes only, illegal if used maliciously
15.2 Exploiting Weak Permissions
Writable service binaries (replace with malicious batch)
Writable startup folders
DLL search order hijacking
15.3 Token Impersonation (Using External Tools)
Batch script calls external tool (e.g., Incognito, custom C# binary)
Elevate from user to SYSTEM
15.4 Scheduled Task Abuse
Tasks running as SYSTEM or admin
Modify task to run batch script
MODULE 16: Lateral Movement
16.1 PsExec-Like Functionality
Batch script copies itself to remote machine
Executes via WMI or scheduled task
Requires admin credentials
16.2 WMI Remote Execution
WMIC /NODE:"remote-pc" PROCESS CALL CREATE "batch-script.bat"
Credential passing
16.3 SMB File Sharing
Copy payload to network share
Execute remotely (WMIC, SCHTASKS /S)
16.4 Pass-the-Hash (Using External Tools)
Batch script orchestrates attack
Calls Mimikatz or other tools
MODULE 17: Data Exfiltration
17.1 File Compression
Compress sensitive files (7-Zip, tar)
Password-protect archive
17.2 Uploading to External Server
FTP upload
HTTP POST (CURL)
Cloud storage (Dropbox API via CURL)
17.3 Email Exfiltration
Send file via email (SMTP using external tool)
Encode file as Base64 (CERTUTIL)
17.4 DNS Exfiltration
Encode data in DNS queries
Extract via monitoring DNS server
Advanced technique, stealthy
17.5 Steganography
Hide data in image file (using external tool)
Batch script automates embedding
MODULE 18: Covering Tracks
18.1 Clearing Event Logs
WEVTUTIL command (clear specific logs)
Clear all logs (dangerous, obvious)
18.2 Deleting Files Securely
Simple delete (DEL, recoverable)
Secure delete (overwrite with random data, SDelete tool)
18.3 Timestamp Manipulation
Modify file timestamps (using PowerShell or external tool)
Match original timestamps (before and after)
18.4 Disabling Logging
Stop Windows Event Log service (risky, detectable)
Modify audit policies
MODULE 19: Malware Analysis (Defensive)
19.1 Static Analysis
Examine batch script without executing
Extract IOCs (IPs, URLs, file paths)
Deobfuscate (decode Base64, reverse string manipulation)
19.2 Dynamic Analysis (Sandboxing)
Run script in VM
Monitor file system changes (Process Monitor)
Monitor registry changes
Monitor network traffic (Wireshark)
19.3 Behavioral Analysis
What does the script DO? (persistence, exfil, destruction)
Identify malicious patterns
19.4 Signature Creation
Create YARA rule for batch malware
Identify unique strings, patterns
19.5 Remediation
Remove persistence mechanisms (registry, scheduled tasks)
Delete dropped files
Restore modified settings
MODULE 20: Payload Development
20.1 Reverse Shell (Batch-Based)
Connect back to attacker machine
Execute commands remotely
Using NETCAT or PowerShell
20.2 Keylogger (Batch as Dropper)
Batch script downloads/executes keylogger
Logs keystrokes to file
Exfiltrates periodically
20.3 Ransomware Simulation (Educational)
Encrypt files (using CIPHER or external tool)
Display ransom note
Decrypt on "payment" (password input)
Disclaimer: Illegal to deploy without consent, educational only
20.4 Backdoor
Persistent access mechanism
Hidden communication channel
Command execution via HTTP, DNS, etc.
20.5 Dropper/Downloader
Batch script downloads second-stage payload
Executes payload
Deletes itself (cover tracks)
MODULE 21: Anti-Forensics
21.1 Fileless Malware Techniques
Execute PowerShell in memory (no file written to disk)
Load DLL reflectively
21.2 Living-Off-the-Land Binaries (LOLBins)
Use legitimate Windows tools for malicious purposes
Examples: CERTUTIL, MSHTA, REGSVR32, WMIC
21.3 Encoding and Obfuscation
Base64 encoding (CERTUTIL)
XOR encryption
Variable name randomization
String splitting and concatenation
21.4 Process Injection (Batch as Orchestrator)
Batch script calls external tool (injects DLL into process)
Evades detection
MODULE 22: Red Team Operations
22.1 Phishing Payloads
Batch script disguised as legitimate file (document.bat.exe)
Social engineering (naming, icons)
22.2 USB Drop Attacks
Autorun batch script on USB insert
Payloads (reverse shell, keylogger, exfiltrator)
22.3 Physical Access Attacks
Bootable USB with batch scripts
Modify startup scripts (if physical access)
22.4 Post-Exploitation Framework Integration
Batch script as stage-1 (downloads Metasploit/Cobalt Strike beacon)
Executes in memory
MODULE 23: Defensive Batch Scripting
23.1 Security Hardening Scripts
Disable unnecessary services
Configure Windows Firewall
Apply security policies (via registry or GPO)
23.2 Intrusion Detection
Monitor critical files for changes (hash comparison)
Alert on unauthorized access attempts
Log anomalies
23.3 Automated Incident Response
Isolate infected machine (disable network)
Kill malicious processes
Collect forensic artifacts (logs, memory dumps)
23.4 Compliance Auditing
Check system configuration against baseline
Generate compliance report
Remediate non-compliant settings
FINAL MODULE 24: Best Practices and Resources
24.1 Code Organization
Modular design (functions for reusability)
Meaningful variable names
Consistent indentation and formatting
24.2 Security Considerations
Never hardcode passwords (use encrypted storage or prompt)
Validate user input (prevent injection attacks)
Least privilege principle (don't run as admin unless necessary)
24.3 Performance Optimization
Minimize loops (expensive operations)
Use GOTO sparingly (spaghetti code risk)
Leverage external tools when batch is inefficient
24.4 Cross-Version Compatibility
Test on Windows 7, 10, 11, Server versions
Use conditional logic for OS-specific features
24.5 Documentation and Commenting
Document each function's purpose
Explain non-obvious logic
Include usage examples
24.6 Resources
SS64.com (comprehensive batch reference)
DosTips.com (community forum, advanced techniques)
GitHub repositories (batch script examples)
Windows Command-Line Reference (Microsoft Docs)