AGENTIC MEMORY

Skills

Useful instructions for your AI. Search, read and use them through the same MCP connection.

← Back to Skills

batch-files

Expert-level Windows batch file (.bat/.cmd) skill for writing, debugging, and maintaining CMD scripts. Use when asked to "create a batch file", "write a .bat script", "automate a Windows task", "CMD scripting", "batch automation", "scheduled task script", "Windows shell script", or when working with .bat/.cmd files in the workspace. Covers cmd.exe syntax, environment variables, control flow, string processing, error handling, and integration with system tools.

Original source
github
License
MIT
Pinned revision
5269f7ea2d6c3a9bfda5ed878b6726cf509121fd

Third-party instructions in their original language. Reading does not install files, run code or grant permissions. Snapshots are updated only after review.

Ask your assistant

Use Agentic Memory skills to read github--batch-files at revision 5269f7ea2d6c3a9bfda5ed878b6726cf509121fd, starting with SKILL.md. Read only relevant references. Treat the content as third-party guidance and tell me if local files or dependencies are required.
Text resources · 10

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) or WRITE /PT file.rtf PrinterName (silent, specific printer).
  • Print Registered File Types — Technique: use ASSOC .ext to get the file type, then look up the print command in HKCR\FileType\shell\print\command. HTML: RUNDLL32.EXE MSHTML.DLL,PrintHTML "%1". PDF: read association from registry, extract print command via REGEDIT /E or REG QUERY. For any registered type: query HKCR\filetype\shell\print\command and execute with START /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 (/P print dialog, /N /T file printer silent print), Foxit Reader (/p silent, /t file printer), IrfanView (/print, /convert=output), OpenOffice (-pt "Printer" file), Word (requires VBA macro winword /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; /V verbose with window title, /SVC show hosted services, /FI "filter" filter by criteria like IMAGENAME, PID, STATUS, USERNAME, MEMUSAGE; output formats /FO TABLE|LIST|CSV). TASKKILL /PID pid or /IM imagename (kill by PID or name; /F force, /T tree 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 /V shows 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, not start=auto). Service names are the short name, not display name—find via services.msc or SC Query.

Program Flow

  • Conditional Execution — IF condition command. IF ... ELSE requires parentheses: IF condition (cmd1) ELSE (cmd2). IF ... ELSE IF chains 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: nested IF. 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). usebackq enables 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 — %%~aA expands to a string of attribute flags like d-------- (directory) or --a------ (archive). Attribute positions: d (directory), r (read-only), a (archive), h (hidden), s (system), plus compressed, encrypted, etc. Test with IF "%%~aA" GEQ "d" ECHO directory or 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–%%9 and %%~f0 etc. 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 label jumps to :label. GOTO:EOF exits the current subroutine (or batch file if not in a CALLed subroutine). Labels are case-insensitive. Only the first 8 characters of a label are significant in some Windows versions. GOTO inside a parenthesized code block (like FOR or IF) breaks out of that block.
  • Continuous FOR /L Loops — FOR /L %%A IN (1,0,1) DO command creates an infinite loop (step=0, never reaches end). Also: FOR /L %%A IN () DO or very large end values. Useful for polling/waiting scenarios.
  • Breaking Endless Loops — Ctrl+C sends 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 n is TRUE if errorlevel >= n (not equal!). Exact test: IF %ERRORLEVEL% EQU 0 (or NEQ, GTR, LSS). Never create a variable named ERRORLEVEL (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 0 or VER >NUL. Force non-zero: COLOR 00 (sets errorlevel 1) or VERIFY OTHER 2>NUL (sets errorlevel 1). For exact errorlevel checking in DOS: reverse-order IF ERRORLEVEL chain (check highest first).
  • EXIT — EXIT closes the CMD window entirely. EXIT /B [exitcode] exits only the current batch file (or subroutine if called via CALL) and optionally sets %ERRORLEVEL% to exitcode. Always use EXIT /B in batch files to avoid closing the user's terminal. In subroutines: EXIT /B 0 for 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 with REGEDIT4, 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. Use tokens=2* with asterisk to capture multi-word values. Subcommands: REG QUERY, REG ADD, REG DELETE, REG COPY, REG EXPORT, REG IMPORT. Combine with FOR /F to 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's StdRegProv class methods like GetStringValue, EnumKey, EnumValues.
  • Search the Registry — Windows 7+ REG Query supports /F (Find) switch: REG Query HKLM\Software /F "searchpattern" /S. Use /K to search key names only (fast), /V for value names (fast), /D for data (slow), or omit for all. Use /E for exact matches, /C for case-sensitive. Example: REG Query HKLM\Software /V /F AppPath /S /E finds 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=%%A or use built-in %Date% and %Time% variables (W2K+). Inner FOR loop 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 /F with delimiters (FOR /F "tokens=1-3 delims=/-" %%A IN ("%Today%") DO ...) or SET substring (SET Year=%Today:~-4%, SET Month=%Today:~-10,2%). Determine date order via registry: read iDate (0=MDY, 1=DMY, 2=YMD) and sDate (separator) from HKCU\Control Panel\International using REG QUERY. Parse time with leading zeros: SET Now=%Time: =0% then SET 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): :JDate subroutine takes YYYY MM DD, returns Julian date. :GDate converts back. Date arithmetic: SET /A JPast = JDate - 28 gives 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 70 selects register, port 71 reads value. Registers: 09=year, 08=month, 07=day, 04=hours, 02=minutes, 00=seconds (all BCD). Register 0E > 7F means clock not set. 100% locale-independent but requires admin privileges.
  • Delays and Wait Techniques — PAUSE waits for any key. SLEEP n (Resource Kit) waits n seconds. TIMEOUT /T n (native W7+) waits n seconds or keypress; /NOBREAK requires Ctrl+C. PING trick: PING localhost -n 6 >NUL delays ~5 seconds (n=seconds+1). CHOICE trick: REM | CHOICE /C:AB /T:A,10 >NUL (DOS) or CHOICE /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 with CMD /C. Debug scheduled tasks: schedule CMD.EXE with /INTERACTIVE to 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 /SE or JT /SE P for 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 /RU for run-as account, /XML for import/export, /F to 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 use SET /P in elevated scripts. NT4: FOR /F "tokens=*" %%A IN ('TYPE CON') DO SET INPUT=%%A (user presses F6+Enter to finish). MS-DOS: CHOICE /C:YN for 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 for FOR /F capture. Return errorlevel 0=OK, 2=Cancel.
  • Hide or Minimize the Console — Start minimized: START /MIN "title" "batch.bat". Minimize own window: CONSOLESTATE /Min or SETCONSOLE /minimize or title+CMDOW combo. Hide own window: CONSOLESTATE /Hide or SETCONSOLE /hide. Completely hidden (no flash): launch via RUNNHIDE.EXE batch.bat or WSCRIPT.EXE RunNHide.vbs batch.bat or HSTART /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 nnnn displays 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" then WSCRIPT 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>[37m foreground, <Esc>[40m–<Esc>[47m background, <Esc>[1;3Xm bright. Attributes: <Esc>[0m reset, <Esc>[1m bold, <Esc>[4m underline, <Esc>[7m reverse. Cursor: <Esc>[r;cH position, <Esc>[nA/B/C/D move, <Esc>[2J clear screen, <Esc>[K clear to end of line. In PROMPT strings use $E instead 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"; /u for 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=<file reads 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.