NANDHOO.

Windows Batch Scripting

Chapter 14: Windows Batch Scripting

While Unix-like systems dominate servers, Windows has a long history of automation through Batch Scripting. Although newer tools like PowerShell and WSL are more powerful, Batch remains essential for legacy support, simple automation, and environments where PowerShell is restricted.

I. Syntax and Mental Model

Batch is fundamentally different from Bash. It is case-insensitive and uses percent signs (%) to denote variables.

BASH (Unix/POSIX)VAR="hello"echo "VAR"</text><text x="30" y="120" font-family="monospace" font-size="10" fill="#1e40af">[[ A == $B ]] && ...ls -lahBATCH (Windows CMD)SET VAR=helloECHO %VAR%IF "%A%"=="%B%" ( ... )DIR /S /B

II. Variable Management and Scoping

1. The SETLOCAL Command

By default, variables set in a Batch script persist in the CMD session even after the script ends. To prevent this, use SETLOCAL.

@echo off
setlocal
SET MY_APP_VAR=hidden
:: Logic here
endlocal
:: MY_APP_VAR is now cleared

2. Delayed Expansion

A common pitfall in Batch is that variables inside a loop are expanded when the loop starts, not when each line runs. To fix this, use EnableDelayedExpansion and exclamation marks (!).

@echo off
setlocal enabledelayedexpansion
SET COUNT=0
FOR /L %%i IN (1,1,5) DO (
    SET /A COUNT+=1
    echo Current count: !COUNT!
)

III. Control Flow: Logic and Loops

1. Conditionals (IF)

Note the importance of double quotes around variables to handle empty strings or spaces.

IF EXIST "config.ini" (
    echo Configuration found.
) ELSE (
    echo Error: config.ini is missing.
    exit /b 1
)

2. Advanced Loops (FOR)

The FOR loop in Batch is extremely powerful but has complex syntax.

  • /F: Process file contents.
  • /R: Recurse through subdirectories.
  • /L: Iterative range (Start, Step, End).
:: Process a CSV file
FOR /F "tokens=1,2 delims=," %%a IN (users.csv) DO (
    echo User: %%a Email: %%b
)

IV. Professional Windows Tools

  • ROBOCOPY: The standard for robust file synchronization.
    • robocopy C:\Source D:\Backup /MIR /MT:8 (Mirrors source to destination with 8 threads).
  • FINDSTR: The Windows equivalent of grep.
  • WMIC: (Windows Management Instrumentation) Used to query system info (like serial numbers or CPU load) from the CLI.

V. Scripting Best Practices

  1. Always use @echo off: Prevents the command prompt from cluttering your output with the code itself.
  2. Use :: or REM for comments: Document your logic.
  3. Use pause at the end: Essential if you are running scripts by double-clicking the file, so you can see the result before the window closes.
  4. Handle Exit Codes: Use exit /b %ERRORLEVEL% to return the status of your script back to the caller.

In the next chapter, we'll learn how to unify these worlds using WSL and Cross-Platform Strategies.