references/batch-files-and-functions.md · 48000
e date-based log folders and append login events: log %COMPUTERNAME%, %USERNAME%, date/time. Capture IP and MAC: IPCONFIG /ALL parsed with FOR /F, or WMIC NIC Where NetEnabled=TRUE Get MACAddress. Check antivirus status via WMI SecurityCenter namespace.
- Login Script Best Practices — Keep scripts lean; avoid bloating with unnecessary operations. Skip mapping when connections already exist. Do not map drives on servers. Use dedicated Terminal Server login scripts separate from regular workstation scripts. Test thoroughly across different Windows versions.
- Active Directory Command-Line Tools (DS Tools) —
DSQUERY(find AD objects:DSQUERY USER -name "John*"),DSGET(read properties:DSGET USER "CN=John,DC=corp,DC=com" -email),DSADD(create objects),DSMOD(modify),DSRM(delete),DSMOVE(move/rename). All accept distinguished name (DN) format. Pipe results:DSQUERY USER -inactive 12 | DSMOD USER -disabled yes.
Printing
- Print Text Files — Classic:
PRINT myfile.txt /D:LPT1(requires LPT/COM port). Modern:NOTEPAD /P file.txt(default printer, any text file regardless of association). Wordpad:WRITE /P file.rtf(with print dialog) orWRITE /PT file.rtf PrinterName(silent, specific printer). - Print Registered File Types — Technique: use
ASSOC .extto get the file type, then look up the print command inHKCR\FileType\shell\print\command. HTML:RUNDLL32.EXE MSHTML.DLL,PrintHTML "%1". PDF: read association from registry, extract print command viaREGEDIT /EorREG QUERY. For any registered type: queryHKCR\filetype\shell\print\commandand execute withSTART /MIN. File association parameters:%1(full path),%L(long name),%W(parent folder). - Command-Line Switches for Applications — Extensive collection of print/open/convert switches: Adobe Reader (
/Pprint dialog,/N /T file printersilent print), Foxit Reader (/psilent,/t file printer), IrfanView (/print,/convert=output), OpenOffice (-pt "Printer" file), Word (requires VBA macrowinword /mPrintDefault /q /n), Notepad (/P), Wordpad (/P,/PT), PowerPoint (/PT "Printer" "" "" "File"). Most programs accept the file path as first argument to open it. - Command-Line Printer Control (PRINTUI.DLL) —
RUNDLL32.EXE PRINTUI.DLL,PrintUIEntry [options](Windows 7 shorthand:PRINTUI.EXE [options]). Install printer:/if /b "Name" /f ntprint.inf /r "port:" /m "Model". Delete:/dl /n "Name". Set default:/y /n "Name". Get/set settings:/Xg//Xs. Backup:/Ss /n "printer" /a "file.dat". Restore:/Sr /n "printer" /a "file.dat". Always returns errorlevel 0 — verify success by exporting settings to file and checking existence. Migrate printers: PrintMig 3.1 (W2K/XP/2003) or PRINTBRM (W7/2008+). - DDE Command-Line Control — Programs that act as DDE servers can be controlled from the command line using DDE commands. Tools like CMCDDE and ClassExec send DDE execute/request commands to running applications. Useful for controlling Office apps that lack direct print commands.
- Printer Management Scripts — Windows ships with VBScript printer management scripts in
%windir%\System32\(pattern*prn*.vbs):prnmngr.vbs(add/delete/list printers),prncnfg.vbs(configure),prnport.vbs(manage ports),prndrvr.vbs(manage drivers),prnjobs.vbs(manage print jobs).
Processes and Services
- Managing Processes — Native (XP+):
TASKLIST(list processes;/Vverbose with window title,/SVCshow hosted services,/FI "filter"filter by criteria likeIMAGENAME,PID,STATUS,USERNAME,MEMUSAGE; output formats/FO TABLE|LIST|CSV).TASKKILL /PID pidor/IM imagename(kill by PID or name;/Fforce,/Ttree kill including children). Resource Kit alternatives:KILL pid|pattern,TLIST [-t](tree view),PULIST(process+user). SysInternals:PSKILL [\\remote] pid|name,PSLIST [-d|-m|-x|-t|-s]. Determine own PID:FOR /F "tokens=2" %%A IN ('TASKLIST /V ^| FIND /I "%~0"') DO SET MyPID=%%A(works because TASKLIST/Vshows CMD window title which contains the batch file path). - Shutdown, Reboot, Logoff —
SHUTDOWN /s /t 60 /c "message"(shutdown in 60s with warning),SHUTDOWN /p(immediate),SHUTDOWN /l(logoff),SHUTDOWN /r /t 0(immediate reboot),SHUTDOWN /h(hibernate),SHUTDOWN /a(abort pending shutdown). WMIC:WMIC OS Where Primary=TRUE Call Shutdown|Reboot|Win32Shutdown. Win32Shutdown codes: 0=Logoff, 1=Shutdown, 2=Reboot, +4=Force, 8=Poweroff. Lock workstation:RUNDLL32 USER32.DLL,LockWorkStation. Sleep:RUNDLL32 powrprof.dll,SetSuspendState Sleep. PowerShell:Restart-Computer [-Force],Stop-Computer [-Force],Stop-Computer -ComputerName "remote". SysInternals PSSHUTDOWN for remote machines. - SC (Service Controller) —
SC \\computer [command] [service] [options]. Commands:query(status),start,stop,config(change settings),description,failure(recovery actions),delete,create,qc(query config),qdescription,qfailure. Change startup:SC Config servicename start= auto|disabled|demand. Recovery:SC Failure servicename actions= restart/60000/restart/60000// reset= 120(restart after 1 min on first two failures, no action after). Important: space after=is mandatory (start= auto, notstart=auto). Service names are the short name, not display name—find viaservices.mscorSC Query.
Program Flow
- Conditional Execution —
IF condition command.IF ... ELSErequires parentheses:IF condition (cmd1) ELSE (cmd2).IF ... ELSE IFchains via:IF cond1 (cmd1) ELSE IF cond2 (cmd2) ELSE (cmd3). Command chaining:&(always sequential),&&(execute next only on success/errorlevel 0),||(execute next only on failure/non-zero errorlevel). Combine:(cmd1 && cmd2 && cmd3) || ECHO Error occurred. Logical AND in conditions: nestedIF. Logical OR: set temp variable per condition, test final value. - FOR Loops (DOS and NT) — Basic:
FOR %%A IN (set) DO command.FOR /D %%A IN (pattern) DO(directories only).FOR /R [path] %%A IN (pattern) DO(recursive tree walk).FOR /L %%A IN (start,step,end) DO(numeric range).FOR /F "options" %%A IN (source) DO(parse files/strings/commands). At command prompt use%A; in batch files use%%A. Variables are single-letter, case-sensitive (%%A≠%%a). - FOR /F Details —
tokens=1,3*extracts columns 1 and 3 into%%A/%%B, remainder into%%C.delims=,;sets delimiters.eol=(comment character).skip=n(skip header lines).usebackqenables back-quoted commands and double-quoted filenames. Variable modifiers:%%~fA(full path),%%~dpA(drive+path),%%~nxA(name+ext),%%~zA(file size),%%~tA(timestamp),%%~aA(attributes),%%~$PATH:A(search PATH). Modifiers are combinable. - File Attributes in FOR —
%%~aAexpands to a string of attribute flags liked--------(directory) or--a------(archive). Attribute positions:d(directory),r(read-only),a(archive),h(hidden),s(system), plus compressed, encrypted, etc. Test withIF "%%~aA" GEQ "d" ECHO directoryor parse specific character positions. - Extended FOR Variables — Punctuation characters can serve as FOR variable names:
%%~f#,%%~dp$PATH:!, etc. This allows nested FOR loops without running out of letter variables. Numbers as FOR variables:%%0–%%9and%%~f0etc. work in some contexts but conflict with batch parameters%0–%9. - Mimic While Loops — Do...Until:
:Loop/ do work /IF NOT condition GOTO Loop. Do...While::Loop/IF condition GOTO End/ do work /GOTO Loop/:End. Use unique label names with numeric suffixes (:Loop1,:Loop2) to avoid conflicts. - GOTO —
GOTO labeljumps to:label.GOTO:EOFexits the current subroutine (or batch file if not in aCALLed subroutine). Labels are case-insensitive. Only the first 8 characters of a label are significant in some Windows versions.GOTOinside a parenthesized code block (likeFORorIF) breaks out of that block. - Continuous FOR /L Loops —
FOR /L %%A IN (1,0,1) DO commandcreates an infinite loop (step=0, never reaches end). Also:FOR /L %%A IN () DOor very large end values. Useful for polling/waiting scenarios. - Breaking Endless Loops —
Ctrl+Csends break signal. From another process:TASKKILL /F /IM cmd.exe /FI "WINDOWTITLE eq BatchTitle". Self-breaking: check a flag file or registry value each iteration,IF EXIST stop.flag GOTO End. - Errorlevels —
IF ERRORLEVEL nis TRUE if errorlevel >= n (not equal!). Exact test:IF %ERRORLEVEL% EQU 0(orNEQ,GTR,LSS). Never create a variable namedERRORLEVEL(shadows the dynamic pseudo-variable). Set errorlevel:EXIT /B n(W2K+, exits batch/subroutine and sets errorlevel to n). Reset to 0:CMD /C EXIT 0orVER >NUL. Force non-zero:COLOR 00(sets errorlevel 1) orVERIFY OTHER 2>NUL(sets errorlevel 1). For exact errorlevel checking in DOS: reverse-orderIF ERRORLEVELchain (check highest first). - EXIT —
EXITcloses the CMD window entirely.EXIT /B [exitcode]exits only the current batch file (or subroutine if called viaCALL) and optionally sets%ERRORLEVEL%to exitcode. Always useEXIT /Bin batch files to avoid closing the user's terminal. In subroutines:EXIT /B 0for success,EXIT /B 1(or other non-zero) for failure.
Registry
- REGEDIT — GUI and command-line registry editor. Import (merge):
REGEDIT /S importfile.REG(silent). Export:REGEDIT /E exportfile.REG "HKEY_XXXX\Whatever Key". Remove tree via .REG file: prefix key with minus[-HKEY_CURRENT_USER\DummyTree]. Remove single value:"ValueToBeRemoved"=-. Self-contained .REG batch hybrid: start file withREGEDIT4, use semicolons for batch commands (;@ECHO OFF/;REGEDIT.EXE /S "%~f0"/;EXIT), then registry entries below. Warning: always back up registry before editing. - REG.EXE — Command-line registry tool (Resource Kit for NT4, native since XP). Read values with
FOR /F:FOR /F "tokens=2* delims=<TAB> " %%A IN ('REG QUERY "HKCU\Control Panel\International" /v sCountry') DO SET Country=%%B. Usetokens=2*with asterisk to capture multi-word values. Subcommands:REG QUERY,REG ADD,REG DELETE,REG COPY,REG EXPORT,REG IMPORT. Combine withFOR /Fto extract any registry value into environment variables. - WMIC Registry — Check registry access permissions:
WMIC /NameSpace:\\root\default Class StdRegProv Call CheckAccess. Also query registry values programmatically through WMI'sStdRegProvclass methods likeGetStringValue,EnumKey,EnumValues. - Search the Registry — Windows 7+
REG Querysupports/F(Find) switch:REG Query HKLM\Software /F "searchpattern" /S. Use/Kto search key names only (fast),/Vfor value names (fast),/Dfor data (slow), or omit for all. Use/Efor exact matches,/Cfor case-sensitive. Example:REG Query HKLM\Software /V /F AppPath /S /Efinds all values named exactly "AppPath".
Date and Time
- DATE and TIME Basics in NT — Get current date/time:
FOR /F "tokens=*" %%A IN ('DATE /T') DO SET Today=%%Aor use built-in%Date%and%Time%variables (W2K+). InnerFORloop strips day-of-week prefix. Values are locale-dependent (order of day/month, separators, AM/PM vs 24h all depend on regional settings). - Parsing DATE and TIME — Two approaches:
FOR /Fwith delimiters (FOR /F "tokens=1-3 delims=/-" %%A IN ("%Today%") DO ...) orSETsubstring (SET Year=%Today:~-4%,SET Month=%Today:~-10,2%). Determine date order via registry: readiDate(0=MDY, 1=DMY, 2=YMD) andsDate(separator) fromHKCU\Control Panel\InternationalusingREG QUERY. Parse time with leading zeros:SET Now=%Time: =0%thenSET Hours=%Now:~0,2%. Strip leading zeros:SET /A Hours = 100%Hours% %% 100. - Advanced Date Math — Convert dates to Julian day numbers for arithmetic. Fliegel-Van Flandern algorithm in batch (by Ron Bakowski):
:JDatesubroutine takes YYYY MM DD, returns Julian date.:GDateconverts back. Date arithmetic:SET /A JPast = JDate - 28gives date 4 weeks ago. Weekday from Julian:SET /A WD = %JDate% %% 7(0=Monday...6=Sunday). Age in days: subtract birth Julian from today's Julian. - Read the CMOS Real Time Clock — Use DEBUG to read CMOS RTC registers directly (16-bit only, requires 32-bit OS). Port
70selects register, port71reads value. Registers:09=year,08=month,07=day,04=hours,02=minutes,00=seconds (all BCD). Register0E>7Fmeans clock not set. 100% locale-independent but requires admin privileges. - Delays and Wait Techniques —
PAUSEwaits for any key.SLEEP n(Resource Kit) waits n seconds.TIMEOUT /T n(native W7+) waits n seconds or keypress;/NOBREAKrequires Ctrl+C. PING trick:PING localhost -n 6 >NULdelays ~5 seconds (n=seconds+1). CHOICE trick:REM | CHOICE /C:AB /T:A,10 >NUL(DOS) orCHOICE /C:AB /D:A /T:10 >NUL(W10). PowerShell:powershell -Command "Start-Sleep -Seconds %1". - The AT Command — Schedule commands at absolute times (NT Server):
AT [\\computername] time [/INTERACTIVE] [/EVERY:day,...] command. Uses SYSTEM account by default. Batch files must be preceded withCMD /C. Debug scheduled tasks: scheduleCMD.EXEwith/INTERACTIVEto get a visible prompt in the SYSTEM context. Superseded by SCHTASKS in Windows XP+. - JT (Job Tool) — Windows 2000 Resource Kit tool for Task Scheduler command line management. Enumerate tasks:
JT /SEorJT /SE Pfor full details. Add, edit, or remove scheduled jobs on local/remote computers. Command line switches are unintuitive; use JTHelp.bat to generate HTML help. - SCHTASKS — Full-featured task scheduler CLI (XP+). Subcommands:
/Create(schedule new task),/Delete,/Query,/Change,/Run(run immediately),/End(stop running task),/ShowSid. Create example:SCHTASKS /Create /SC DAILY /TN "MyTask" /TR "C:\script.bat" /ST 21:00. Schedule types: MINUTE, HOURLY, DAILY, WEEKLY, MONTHLY, ONCE, ONSTART, ONLOGON, ONIDLE, ONEVENT. Use/RUfor run-as account,/XMLfor import/export,/Fto force overwrite.
User Interaction
- User Input —
SET /P variable=prompt(W2K+) reads a line of user input. Warning: input containing&,<,>,|or"can cause code injection—never useSET /Pin elevated scripts. NT4:FOR /F "tokens=*" %%A IN ('TYPE CON') DO SET INPUT=%%A(user presses F6+Enter to finish). MS-DOS:CHOICE /C:YNfor single-key Yes/No. PowerShell login dialog:FOR /F "tokens=1* delims=;" %%A IN ('PowerShell ./login.ps1 %UserName%') DO (SET Usr=%%A & SET Pwd=%%B). - Neat Dialog Boxes in Batch Files — C# GUI utilities for batch:
MessageBox.exe(popup message, returns clicked button caption),InputBox.exe(text input with optional password masking, regex filtering, timeout),OpenFileBox.exe/SaveFileBox.exe(file dialogs),OpenFolderBox.exe(folder browser),PrinterSelectBox.exe,DateTimeBox.exe,DropDownBox.exe/RadioButtonBox.exe(list selection),MultipleChoiceBox.exe(checkboxes),ColorSelectBox.exe,FontSelectBox.exe,ProgressBarGUI.exe. All write selection to stdout forFOR /Fcapture. Return errorlevel 0=OK, 2=Cancel. - Hide or Minimize the Console — Start minimized:
START /MIN "title" "batch.bat". Minimize own window:CONSOLESTATE /MinorSETCONSOLE /minimizeor title+CMDOW combo. Hide own window:CONSOLESTATE /HideorSETCONSOLE /hide. Completely hidden (no flash): launch viaRUNNHIDE.EXE batch.batorWSCRIPT.EXE RunNHide.vbs batch.batorHSTART /NOCONSOLE "batch.bat". Note: hiding from within the batch always shows a brief console flash; cloaking must start before the batch. - Error Messages in Local Language —
NET HELPMSG nnnndisplays Windows error message number nnnn in the local system language. Generate a complete list:FOR /L %%A IN (0,1,16384) DO (FOR /F "tokens=*" %%B IN ('NET HELPMSG %%A 2^>NUL') DO ECHO %%A %%B). Use these numbers in batch scripts for localized error output without hardcoding translations. - Popup Messages —
MSG.EXE(XP Pro+): send popup to users/sessions. VBScript on-the-fly:> msg.vbs ECHO WScript.Echo "message"thenWSCRIPT msg.vbs. MSHTA one-liner:MSHTA vbscript:Close(MsgBox("message",vbOKOnly,"title")). PowerShell one-liner:FOR /F "usebackq" %%A IN (\PowerShell -Command "Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.MessageBox]::Show('message','title','YesNo','Question')"`) DO SET Answer=%%A`. Result is button caption string (Yes, No, OK, Cancel). - ANSI Colors and Escape Sequences — ANSI.SYS required in DOS; built into Windows 10+ CMD.EXE natively. Escape character = ASCII 27. Insert in batch via FORFILES:
FORFILES /P %~dps0 /M %~nxs0 /C "CMD /C ECHO 0x1B[1;31m Red Text 0x1B[0m". Color codes:<Esc>[30m–<Esc>[37mforeground,<Esc>[40m–<Esc>[47mbackground,<Esc>[1;3Xmbright. Attributes:<Esc>[0mreset,<Esc>[1mbold,<Esc>[4munderline,<Esc>[7mreverse. Cursor:<Esc>[r;cHposition,<Esc>[nA/B/C/Dmove,<Esc>[2Jclear screen,<Esc>[Kclear to end of line. In PROMPT strings use$Einstead of the Esc character.
Miscellaneous and Collections
- UNIX Ports (WHICH, TEE, CUT) — Batch/Rexx/Perl/PowerShell/VBScript ports of essential Unix utilities. WHICH: locate executables in PATH (handles DOSKEY macros and CMD internals). TEE: split stdout to both screen and file simultaneously. CUT: extract columns/fields from text. Also includes TRUE/FALSE utilities for explicit errorlevel setting. Available as native batch (.bat), compiled Perl (.exe), and multiple scripting language versions.
- Undocumented NT Commands —
ACINIUPD(W2K Server): update INI files from command line (ACINIUPD /e "file.ini" "section" key "value";/ufor user directory; admin-only).SFC /SCANNOW: scan and replace corrupted protected system files.TSSHUTDN(Terminal Server): controlled server shutdown with user notification, reboot, and powerdown options. - DEBUG — 16-bit DOS debugger repurposed for batch scripting (32-bit OS only; unavailable on 64-bit). Read CMOS Real Time Clock (locale-independent date/time). Read VideoROM manufacturer info. Read I/O port addresses for COM/LPT ports. Check CapsLock/NumLock/ScrollLock status. Create tiny .COM utilities (e.g., REPLY.COM for user input, RESET.COM for reboot). Embed scripts in batch:
DEBUG < %0.BAT/GOTO Around/ script /:Around. - Clever Tips and Tricks — CMD /C quoting quirk:
CMD /C @"command" "arg"(prefix@to prevent misparse when first and last chars are quotes). Elevation check:WHOAMI /GROUPS | FIND "12288"(works in both 32-bit and 64-bit).PUSHD "%~dp0"auto-maps UNC paths to drive letters (works with RUNAS, PSEXEC, UAC).SET /P var=<filereads first line of file into variable. Large number math: FOR loop inserts spaces between digits for per-digit multiplication. FOR /F supports 31 tokens (not just 26) using escaped special characters like%%^^,%%_,%%\``. Swap mouse:RUNDLL32 USER32.DLL,SwapMouseButton. Resolve hostname:FOR /F "tokens=2" %%A IN ('PING -a %1 ^| FIND "[%1]"') DO ECHO %%A. Group commands for single redirect:(cmd1 & cmd2 & cmd3) > log.txt`. - ANSI Art and Console Colors — Use ANSI escape sequences to create colored text screens and animations. ANSI.SYS (DOS) or Windows 10 built-in support. FORFILES technique generates Esc characters on-the-fly. Alternatives:
KOLOR.EXE(set color for text selection in 32/64-bit), BG by Carlos M. (modern BATCHMAN replacement), EKKO by Norman De Forest (ECHO enhancement with PROMPT-like color functions without ANSI driver). - AUTOEXEC.BAT — Automatic startup batch file executed by COMMAND.COM on boot (MS-DOS/Windows 9x). Used to set PATH, load TSRs, configure environment variables, and initialize devices. Not used in Windows NT+ (replaced by registry Run keys and startup folders).
- PHP-Based Batch Files — Technique for mixing PHP code with batch files. PHP CLI processes the script while batch commands are hidden in PHP comments. Useful for leveraging PHP string functions, regex, and web capabilities from within a .bat wrapper.
- Batch HowTos and Sample Collections — Curated collections of batch file techniques, how-to guides, and example scripts covering common Windows administration tasks. Topics include inventory scripts, login scripts, admin tools, network administration, and community-contributed solutions. "Poor Man's Admin Tools" provides lightweight batch-only alternatives to commercial utilities (PMChoice, PMSleep, PMSoon, and others).
- Useful NT Commands for Administrators — Reference of NT commands commonly used in administration batch scripts, including NET commands, SC (service control), TASKLIST/TASKKILL, WMIC, REG, SCHTASKS, ROBOCOPY, ICACLS, and system information utilities.