A note to self by Michiel van Oosterhout, last updated on .

The official documentation covers all built-in commands and command-line programs, but does not cover the syntax. One of the best references for Windows Command Processor script syntax is Windows Batch Scripting. SS64.com contains useful how-to guides and examples.

Syntax

  • @ prevents echoing the command line's remaining commands.
  • echo( prints a blank line
  • echo(on prints on (also works for off and /?)
  • < nul (set /p _=hello) prints hello without a trailing CR,LF
  • %var:~n,m% substring starting at index n and ending at index n+m (negative numbers count from the end of the string)
  • %var:find=replace% replaces all occurrences of find with replace (case-insensitive, find may start with the wildcard *)
  • if <cond1> if <cond2> (<commands>) execute <commands> if cond1 AND cond2 (does not support else)
  • Variable substitution:
    • %~1 removes surrounding double quotes (C:\Program Files\Git\bin\git.exe)
    • %~f1 fully qualified path (C:\Program Files\Git\bin\git.exe)
    • %~d1 drive letter (C:)
    • %~p1 path (\Program Files\Git\bin\)
    • %~n1 file name (git)
    • %~x1 file extension (.exe)
    • %~s1 replace names with short names (C:\PROGRA~1\Git\bin\git.exe)
    • %~a1 file attributes (--a------,)
    • %~t1 date/time (12/21/2022 01:47 PM)
    • %~z1 file size in bytes (45104)
    • %~$var:1 expand file name to first path found in var (C:\Program Files\Git\cmd\git.exe)
    • %~ftza1 same as output of dir command
  • for /l %%a in (start,step,end) do command while start does not equal end, execute command and add step to start
  • for /f %%l in ('command') executes command in a separate instance of cmd.exe
  • for /f %%e in ('echo prompt $E^| cmd') do (set esc=%%e) sets esc to ^[ (by reading the last output of cmd after changing its prompt to ^[)

Other

  • F7: show history
    • Esc: dismiss history
    • F9: select command-line by number
    • Enter: execute command line
    • or : edit command line

Links