references/batch-files-and-functions.md · 24000
essionfor integer math (Windows NT 4+): supports(), * / %, + -, << >>, & ^ |, assignment operators. Numeric literals: 0xhex,0bbinary,0octal — beware08/09are invalid octal. Limited to 16- or 32-bit integers depending on Windows version.SET /P variable=prompt` (Windows 2000+) prompts for input; pressing Enter alone leaves variable unchanged.
NT SET Features — String substitution: %PATH:str1=str2% replaces occurrences (case-insensitive in XP+). str1 can begin with * to match from start. Substrings: %PATH:~10,5% extracts 5 chars at offset 10. Negative offsets: %PATH:~-10% last 10 chars, %PATH:~0,-2% all but last 2.
Dynamic Environment Variables — Computed on each expansion, don't appear in SET output: %CD% (current directory), %DATE%, %TIME%, %RANDOM% (0–32767), %ERRORLEVEL%, %CMDCMDLINE%, %CMDEXTVERSION%, %HIGHESTNUMANODENUMBER%. Hidden dynamics (discovered via SET ""): %=C:% (current dir on C:), %=ExitCode% (hex last exit), %=ExitCodeAscii%, %__APPDIR__% (exe parent folder with trailing \), %__CD__% (current dir with trailing \). If user sets a dynamic variable name, it overrides the dynamic value; unsetting restores it.
Verify if Variables are Defined — IF DEFINED varname (requires Command Extensions). Safer than IF "%var%"=="" which fails on values with doublequotes or special chars. Hidden/dynamic variables (DATE, CD, RANDOM, etc.) report as defined via IF DEFINED but SET varname returns "not defined" unless explicitly set. Check if dynamic vs static: SET Date >NUL 2>&1 — errorlevel 1 means still dynamic. Demo: FOR %%A IN (COMSPEC __APPDIR__ CD DATE ERRORLEVEL RANDOM TIME) DO (IF DEFINED %%A (...)).
Validate Variables — Check string formats with FINDSTR or FOR /F delims tricks. Hexadecimal: FOR /F "delims=0123456789AaBbCcDdEeFf" %%A IN ("%~1") DO ECHO NOT hex or SET /A "=0x%~1". Decimal: ECHO.%~1| FINDSTR /R /X /C:"[0-9][0-9]*". IPv4: validate 4 dot-separated blocks 0–255 with nested checks (reject 256+, reject non-numeric, reject wrong block count). IPv6: remove interface part (%% and after), check no :::, count colon-separated blocks (8 without ::, fewer with :: allowed), validate each block as 1–4 hex digits. MAC: 6 groups of 2 hex digits separated by : or -. ISBN-13: checksum by alternating multiply by 1 and 3. Luhn algorithm: for credit cards, IMEI — double alternating digits, subtract 9 if >9, compare checksum.
Delayed Variable Expansion — Variables expanded with %var% are resolved when the line is READ, not when executed. Inside FOR loops and code blocks (...), this means %var% gets the value from before the block runs. Enable with SETLOCAL ENABLEDELAYEDEXPANSION or CMD /V:ON. Use !var! instead of %var% for execution-time expansion. Example: SET LIST= then FOR %A IN (*) DO SET LIST=!LIST! %A builds cumulative list. Layout note: FOR %%A IN (...) DO (SET X=%X%%%A) is identical to single-line form — both expand %X% before the loop runs. Bug exists in delayed expansion with certain edge cases.
Escape Characters — Percent % escaped by doubling %% in batch files. Caret ^ escapes special chars in CMD.EXE: ^&, ^<, ^>, ^|, ^^, ^(, ^). Doublequoting also protects special chars but quotes are passed to commands. Exclamation marks (with delayed expansion): use ^^! (double caret needed — single caret consumed in first pass, exclamation in second delayed-expansion pass). FIND escapes doublequotes by doubling: """". FINDSTR regex escapes: \\, \[, \], \", \., \*, \?. CALL adds extra caret escaping to arguments — always test when passing escaped strings to CALL.
Command Line Parameters — %0 is program name, %1–%9 are arguments. %10 is NOT the 10th arg — it's %1 followed by 0. Use SHIFT to rotate parameters (or SHIFT /n to shift from position n). NT features: %* = all args, %~d1 drive, %~p1 path, %~n1 filename, %~x1 extension, %~f1 full path. %CmdCmdLine% = original CMD invocation. Delimiters: commas/semicolons replaced by spaces (unless in quotes), first / after command replaced by space, multiple spaces collapsed. Loop alternative: FOR %%A IN (%*) DO (handle %%A). Validate with GOTO trick: GOTO:%~1 2>NUL / IF ERRORLEVEL 1 (echo invalid).
Random Numbers — %RANDOM% dynamic variable gives 0–32767 range. Techniques: (1) Native: FOR /F "tokens=*" %%A IN ('VER ^| TIME ^| FINDSTR /R "[.,]"') DO FOR %%B IN (%%A) DO SET Random=%%B (hundredths of seconds, not truly random in loops). (2) PowerShell: FOR /F %%A IN ('powershell.exe -Command "Get-Random -Minimum 1 -Maximum 100"') DO SET Random=%%A. (3) Rexx: rexxtry say Random(min, max). (4) VBScript: Randomize then WScript.Echo Int((6 * Rnd) + 1), capture with FOR /F %%A IN ('CSCRIPT //NoLogo random.vbs') DO SET Random=%%A.
String Processing
Get String Length — No native string length function. Brute force: iterate character positions with !var:~%%A,1! until empty. Successive approximation (faster for long strings): binary search using IF NOT "!var:~N!"=="" at powers of 2 (512, 256, 128, ..., 1), accumulating length. Example brute force: SET len=0 / FOR /L %%A IN (0,1,8191) DO IF NOT "!str:~%%A,1!"=="" SET /A len=%%A+1.
FOR /F Tokens and Delims — FOR /F "tokens=n,m* delims=ccc" %%A IN ('command') DO .... Delimiters split input into tokens; multiple consecutive delimiters treated as one. Leading delimiters before first word are ignored (useful for stripping leading spaces: FOR /F "tokens=*" %%A IN (" text") DO ECHO %%A). First specified token maps to %%A, next to %%B, etc. tokens=* captures entire remainder. Escape pipe/redirect chars inside FOR /F parentheses with caret: ^|, ^>. No escaping needed when chars are inside quoted strings like FIND "<03>". Strip leading zeroes: FOR /F "tokens=* delims=0" %%A IN ("00012") DO ECHO %%A.
String Substitution — %var:str1=str2% replaces all occurrences of str1 with str2 in the variable value. Case-insensitive in XP+. str2 can be empty to delete occurrences. str1 can start with * to match everything from start to first occurrence of remainder. Example: SET var=%var:old=new%.
Substrings — %var:~offset,length% extracts substring. Offset 0-based; negative offset counts from end. %var:~-10% last 10 chars. %var:~0,-2% all but last 2. Length omitted = rest of string.
Convert to Upper or Lower Case — Method 1 (SET substitution with delayed expansion): SET %~1=!%~1:a=A! repeated for each letter A–Z. Call as subroutine: CALL :UpCase VarName. Method 2 (FOR loop, no delayed expansion needed): FOR %%i IN ("a=A" "b=B" ...) DO CALL SET "%1=%%%1:%%~i%%". Title case variant replaces " a= A" (space-prefixed). Method 3 (Brad Thone): exploit case-insensitive substitution — SET _Abet=A B C D...Z then FOR %%Z IN (%_Abet%) DO SET _Tmp=!_Tmp:%%Z=%%Z!. Method 4 (FIND trick): FIND returns "file names" in upper case in "File not found" message — FOR /F "tokens=2 delims=-" %%A IN ('FIND "" "%~1" 2^>^&1') DO SET UpCase=%%A (XP+). Method 5 (DIR /L): DIR /L /B ~%%B converts temp filename to lowercase. PowerShell: ('%*').ToUpper() or ('%*').ToLower(). Warning: all SET-based methods vulnerable to code insertion — validate input first.
Align Text to Display as Tables — Pad strings to fixed width: append N spaces then truncate: SET Line=%%A%FortySpaces% / SET Line=!Line:~0,40!. For dynamic column width, measure longest string first with brute-force length check (iterate positions 0..80, set width to max). Full pattern: SET "EightySpaces=..." / first pass FOR /F finds max length / second pass pads and appends second column. Console width detection: FOR /F "tokens=2 delims=:" %%A IN ('MODE CON ^| FIND "Columns"') DO SET ConsoleWidth=%%A.
Arrays in Batch Files — Simulate arrays using variable naming conventions. SET User lists all vars starting with "User". Create array-like sets: SET __Arr.Key1=Value1, SET __Arr.Key2=Value2. Loop through: FOR /F "tokens=2* delims=.=" %%A IN ('SET __Arr.') DO ECHO %%A = %%B. WMIC example: FOR /F "tokens=*" %%A IN ('WMIC LogicalDisk Where "DeviceID='C:'" Get /Format:list ^| FIND "="') DO SET __Disk.%%A. Use FINDSTR /R /C:"=." to skip empty values (WMIC outputs CR/LF pairs in empty fields). Enumerate with SET __Disk. to list all stored properties. Closest approximation to associative arrays/hashtables in batch language.
Math and Arithmetic
- SET /A Arithmetic —
SET /Asupports add (+), subtract (-), multiply (*), integer divide (/), modulo (%%), bit-shift (<<,>>), bitwise AND (&), OR (|), XOR (^), NOT (~), logical NOT (!), grouping(), and combined assignment operators (+=,-=,*=,/=,%%=,&=,|=,^=,<<=,>>=). Numeric literals: octal prefix0, hex prefix0x. 32-bit signed integer limit (−2,147,483,648 to 2,147,483,647); 16-bit on NT4. No exponentiation operator — use a loop multiplying in a variable. No square root — use binary search or PowerShell. - No Floating Point — Batch has no native floating-point. Workaround: multiply by 100 (or 1000), do integer math, then extract whole and fraction parts via string slicing:
SET Whole=%Result:~0,-2%andSET Frac=%Result:~-2%. For truly large or precise math, embed a PowerShell one-liner:powershell -C "expression". - Big Number Workarounds — For numbers exceeding 32-bit range: (1) chop last N digits for approximate math, (2) split into individual digits for arbitrary-precision add/multiply (e.g., process digit-by-digit with carry), (3) call PowerShell or another language.
- Formatting Numbers — Display hex: repeatedly divide by 16, index into
0123456789ABCDEFhelper string using!Convert:~%Digit%,1!. Display octal: divide by 8 loop. Right-align decimals: pad with spaces then chop with!Align:~-8!. File size limit ~107MB when multiplying by 20 (32-bit overflow). PowerShell.ToString("format")is simpler for complex formatting. - Boolean Logic in Conditions — No AND/OR/XOR for
IFconditions (only for binary math viaSET /A). AND: nestedIFstatements. OR: set a temp variable to 0, set to 1 per matching condition, then test. XOR: too complex with nested IF. Better approach: assign each condition to a binary variable (0 or 1), then useSET /A "ResultAND = %C1% & %C2%",SET /A "ResultOR = %C1% | %C2%",SET /A "ResultXOR = %C1% ^ %C2%". - Leading Zeroes Gotcha —
SET /Atreats numbers with leading0as octal, soSET /A x=08andSET /A x=09cause "invalid number" errors. Always strip leading zeroes before arithmetic. Common techniques: useFOR /Ftokenizing, string manipulation to remove leading zeroes, orSET /A "1%var:~-2% - 100"pattern to force decimal interpretation.
Devices and Hardware
- DOS/NT Device Names — Valid logical devices: AUX, CON, PRN, COM1-4, LPT1-3, NUL. In NT, check if a name is a device:
DIR %1 2>NUL | FIND /I "Volume" >NUL— no volume label means it is a device. In DOS, AUX/CON/PRN are shown with current date/time by DIR, so must be checked separately. - DEVCON — Command-line Device Manager alternative from the Windows Driver Kit (WDK). Key commands:
classes(list setup classes),find/findall(find devices, including disconnected),hwids(list hardware IDs),driverfiles(list driver files),install/remove/enable/disable/restart/rescan,reboot,status,resources,update,dp_add/dp_delete/dp_enum(OEM driver packages). Remote:-m:\\machine. Class filter:=ClassName(e.g.,=USB,=Printer,=DiskDrive). Hardware ID:@hwid. Example:DEVCON FindAll =USBlists all USB devices including disconnected.
Elevated Privileges
- Check Elevation — Multiple techniques: (1)
OPENFILES >NUL 2>&1— fails if not elevated, butOPENFILESis 64-bit only and fails in 32-bit processes on 64-bit Windows. (2)CACLS "%SYSTEMROOT%\system32\config\system"— check errorlevel; works if CACLS is available. (3) Most reliable:WHOAMI /Groups | FIND "12288" >NUL— works correctly regardless of 32/64-bit process. Detect 32-bit process on 64-bit Windows: ifPROCESSOR_ARCHITEW6432is set (equals AMD64), it is a 32-bit process in 64-bit OS. - Set Elevation (UAC Prompt) — Create a temporary VBScript on-the-fly:
Set UAC = CreateObject("Shell.Application")thenUAC.ShellExecute "%~snx0", "%*", "%~sdp0", "runas", 1. This restarts the batch file with elevated privileges. Variables are lost on restart (new process), so test elevation first thing. PowerShell check:[Security.Principal.WindowsPrincipal]([Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator).
Files and Folders
- Rename Files —
REN oldname newnamesupports wildcards:REN *.txt *.bak. Undocumented:REN file.txt *schops the filename after the last occurrence of the character. UseFORloops for complex renaming:FOR %%A IN (*.txt) DO REN "%%A" "%%~nA_backup%%~xA". Rename folders withMOVE oldfolder newfolder. - File Properties via FOR Modifiers —
FOR %%A IN (file) DOwith modifiers:%%~nA(name),%%~xA(extension),%%~snA(short 8.3 name),%%~aA(attributes),%%~dA(drive),%%~zA(size bytes),%%~tA(date/time),%%~dpA(drive+path/parent),%%~fA(full qualified path),%%~$PATH:A(first PATH match). Modifiers are combinable:%%~nxA(name+ext),%%~dpnxA(full path),%%~fsA(full short path). - File and Product Versions —
FILEVER /V filename(from Support Tools) displays file/product version, description, company. Extract version withFOR /F: parse the/Voutput. Comparing dotted version strings: compare each segment numerically (string comparison of1.10vs1.9fails because"10" < "9"alphabetically). - START and File Associations —
START "title" [/D path] [/I] [/MIN] [/MAX] [/WAIT] [/B] [/SEPARATE] [/SHARED] [priority] command [args]. Priority classes:/LOW,/NORMAL,/HIGH,/REALTIME,/ABOVENORMAL,/BELOWNORMAL. File associations viaHKEY_CLASSES_ROOT: parameters%1(file path),%L(long name),%W(working directory).PATHEXTcontrols which extensions are resolved without explicit extension. - Temporary Files — Use
"%TEMP%.\tempfile"(with trailing dot) for safe temp paths. Windows 2000%TEMP%often contains spaces — always quote.RUNASmay change%TEMP%to a read-only location. Create unique temp names with%RANDOM%or%TIME::=%. - PDF Commands — Get page count: ExifTool (
-PageCount), GhostScript (gswin32c -q -dNODISPLAY -c "(file) (r) file runpdfbegin pdfpagecount = quit"), PDFtk (pdftk file dump_data | FIND "NumberOfPages"), or native:TYPE file.pdf | FINDSTR /R /C:"/Type\s*/Page"(approximate). Merge: GhostScript orpdftk file1.pdf file2.pdf cat output merged.pdf. Print: Acrobat Reader/Por/T, Foxit/p, GhostScript, or registered print command. - Check Folder Exists — NT:
IF EXIST "folder\"(trailing backslash). DOS:IF EXIST folder\NUL. More robust:PUSHD "folder" && (POPD & ECHO exists) || ECHO not exists. TheNULtrick may fail with junctions/symlinks in NT.FOR /Dcan also match directories:FOR /D %%A IN (folder) DO ECHO found. - FOR /D and FOR /R —
FOR /D %%A IN (pattern) DO commandmatches directories.FOR /R [path] %%A IN (pattern) DO commandwalks directory trees recursively. Combine:FOR /R "C:\" /D %%A IN (*) DO ECHO %%Alists all subdirectories. - RD (RMDIR) —
RD /S /Q directoryremoves directory tree silently./Sremoves all subdirectories and files./Qsuppresses confirmation. Returns errorlevel 2 if directory not found, 145 if directory not empty (when/Somitted). - Wildcards Quirks —
*matches any characters including none;?matches exactly one character. Quirks: wildcards after the 3rd character of the extension are ignored in some commands. Short 8.3 names can cause unexpected matches (a file with a long name may match via its short name).DIR *~*.*returns unpredictable results.DEL *~*.*is dangerous — may delete unexpected files due to short name matching.
Redirection and Encoding
- FOR /F (File/String/Command Parsing) —
FOR /F "options" %%A IN (source) DO command. Options:tokens=(column selection, e.g.,1,3*),delims=(delimiter chars, default space/tab),eol=(comment char, default;),skip=n(skip first N lines),usebackq(changes quoting: back-quotes for commands, double-quotes for filenames, single-quotes for strings). Sources: filename,"string",`command`(withusebackq), or('command'). Variable modifiers:%%~fA(full path),%%~dpA(drive+path), etc. - Tokens and Delims —
tokens=1,3extracts columns 1 and 3 into%%Aand%%B.tokens=2*gets column 2 in%%Aand remainder in%%B.tokens=1-5gets columns 1–5. Default delimiters: space and tab.delims=,;sets comma and semicolon.delims=(nothing) reads the entire line.eol=must be set to empty (or a char not in data) to avoid skipping lines starting with;. - Redirection —
>(overwrite stdout),>>(append stdout),2>(redirect stderr),2>&1(merge stderr into stdout),1>&2(stdout to stderr),|(pipe stdout). File handles: 0=stdin, 1=stdout, 2=stderr. Place redirection before the command for readability:>file ECHO text. Escape with caret:ECHO text ^> not-redirected. Space before>may get echoed as part of the text. - Streams and Redirection Explained — Three standard streams: Standard Output (handle 1), Standard Error (handle 2), Console (CON).
2>&1merges stderr into stdout for combined piping/capture.>CONbypasses file redirection and always writes to console. Console output fromCLSand some commands cannot be redirected. Best practice:command > logfile 2>&1to capture both streams. Ambiguity: lines ending in1or2before>may be misinterpreted as handle numbers. - TEE Equivalent — No native TEE in Windows. Workaround: pipe to a batch/PowerShell script that writes to both screen and file. Or use port of Unix TEE command. Simple batch approximation: use
FOR /Fto read command output,ECHOto screen and>>filesimultaneously. - Detect File Encoding —
FOR /Floop aborts on ASCII 0 (null) characters present in Unicode files. Test:FOR /F %%A IN (file) DO (ECHO ANSI&GOTO:EOF)— if the loop completes without the ECHO executing, the file is Unicode (contains null bytes that breakFOR /F). - ASCII vs. Unicode Conversion —
TYPEdoes not lock files (useful for copying logs in use). Unicode to ASCII:TYPE unicode.txt > ascii.txt. ASCII to Unicode:CMD /U /C TYPE ascii.txt > unicode.txt. Unicode BOM header: bytes0xFF 0xFE. Convert Unix linefeeds to Windows:TYPE input.txt | MORE /E /P > output.txt. - Base64 Encoding/Decoding —
CERTUTIL.EXE -encode inputfile outputfile.b64(encode to Base64).CERTUTIL.EXE -decode inputfile.b64 outputfile(decode from Base64). Output includes header/footer lines (-----BEGIN CERTIFICATE-----/-----END CERTIFICATE-----) that may need stripping withFINDSTR /V "CERTIFICATE". - Hex Encoding/Decoding —
CERTUTIL.EXE -encodehex inputfile outputfile [format]. Formats: default (hex editor view with offsets and ASCII),4(hex only, no ASCII or offsets),12(single continuous hex line). Decode:CERTUTIL.EXE -decodehex hexfile outputfile. PowerShell alternatives:[Convert]::ToHexString()/[Convert]::FromHexString()(.NET 5+). - File Hashes —
CERTUTIL.EXE -hashfile filename [algorithm]. Algorithms: MD2, MD4, MD5, SHA1 (default), SHA256, SHA384, SHA512. Example:CERTUTIL -hashfile myapp.exe SHA256. Alternative: FCIV (File Checksum Integrity Verifier, unsupported Microsoft tool, MD5/SHA1 only). PowerShell:Get-FileHash -Algorithm SHA256 filename.
Internet and Networking
- Get Default Browser — Manual:
START ms-settings:defaultapps. Programmatic: readHKCU\SOFTWARE\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice\ProgIDviaREG QUERY, returns a value likeFirefoxHTML-308046B0AF4A39CB. Then look up the executable:REG QUERY "HKCR\<ProgID>\shell\open\command"to get the browser path. Old techniques usingASSOC .html/FTYPEno longer work reliably in Windows 10+. - Auto-Download Prompt — Check if a third-party tool exists:
TOOL /? >NUL 2>&1thenIF ERRORLEVEL 1means missing. If tool returns non-zero on/?, use(TOOL /? 2>&1) | FIND /I "copyright" >NULto detect its output. Prompt user:SET /P Download=Download now? [y/N], thenIF /I "%Download%"=="Y" START "title" "https://download-page". Always detect before executing to avoid crypticnot recognizederrors. - E-mail from Batch —
START mailto:[email protected]?subject=Hello%%20World^&body=Message%%20text. Escaping: spaces=%%20, CR/LF=%%0D%%0A, ampersands escaped with caret (^&), double%%for batch. Length limited to max command line (~8191 chars on modern Windows). Only creates the message — user must press Send. For unattended sending: use third-party tools like Blat (SMTP, free) or MailSend (shareware). HTML5 also supports<a href="tel:">and<a href="sms:">. - FTP Scripting —
FTP -s:scriptfile hostnamefor unattended transfers. Script file contains:USER username, password (next line),cd path,binary,prompt n,mget *.*(ormput). Security: create script on-the-fly withECHOredirection, delete after use (TYPE NUL >script.ftp & DEL script.ftp). Check for errors: redirect FTP output to log file, useFINDto search for error messages. Alternatives: WGET (wget ftp://host/filefor anonymous downloads), WinSCP (SFTP/FTP with scripting interface), ScriptFTP (encrypted scripts, self-contained executables). - WMIC (WMI Command Line) — Available XP Pro+ (disabled by default in Windows 11). Commands:
GET(read properties),SET(change),CALL(invoke methods). Output formats:/Format:csv,/Format:list,/Format:htable. Store in variables:FOR /F "tokens=*" %%A IN ('WMIC BIOS Get Manufacturer^,Name /Value ^| FIND "="') DO SET BIOS.%%A.WHEREclause with WQL:WMIC Path Win32_NetworkAdapter Where "PhysicalAdapter=TRUE" Get. Aliases vs full class path:WMIC OS Get=WMIC Path Win32_OperatingSystem Get. Remote:/Node:computer. Non-default namespace:/NameSpace:\\root\other. Registry access possible butREG.EXEis easier. - DMIDecode — Linux/Unix utility ported to Windows for reading DMI/SMBIOS data (hardware info like BIOS, system, baseboard, chassis, processor details) directly from firmware tables without WMI.
- RAS (Remote Access) — Commands for managing dial-up and VPN connections from the command line.
RASDIAL entryname [username password]to connect,RASDIAL /DISCONNECTto disconnect.RASPHONE -h entrynameto hang up. - Terminal Server Commands —
QUERY USER [/SERVER:name](list sessions),QUERY SESSION,LOGOFF sessionid /SERVER:name,TSSHUTDN seconds /SERVER:name /POWERDOWN /DELAY:n /V(shutdown with notification),MSG sessionid message,SHADOW sessionid(remote control). UseCHANGE LOGON /DISABLEto prevent new logons.
Login Scripts and Administration
- Network Drive Mapping —
NET USE G: \\Server\Share /PERSISTENT:Noto map.NET USE G: /DELETEto disconnect. Group-based conditional mapping:NET GROUP "groupname" /DOMAIN | FINDSTR /I "%USERNAME%"then map if found. Always use/PERSISTENT:Noin login scripts to prevent stale mappings. - Network Printer Mapping —
NET USE LPT1 \\Server\Printerto connect a printer port. For non-port-based printing, useRUNDLL32 PRINTUI.DLL,PrintUIEntry /in /n \\Server\Printer. Set default printer:WMIC Path Win32_Printer Where Name='PrinterName' Call SetDefaultPrinter. - Log Computer Access — Creat