batch-files

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Batch Files

批处理文件

A comprehensive skill for creating, editing, debugging, and maintaining Windows batch files (.bat/.cmd) using cmd.exe. Applies to CLI tool development, system administration automation, scheduled tasks, file operations scripting, and PATH-based executable scripts.
这是一套用于使用cmd.exe创建、编辑、调试和维护Windows批处理文件(.bat/.cmd)的完整技能体系,适用于CLI工具开发、系统管理自动化、计划任务、文件操作脚本编写以及基于PATH的可执行脚本开发。

When to Use This Skill

适用场景

  • Creating or editing
    .bat
    or
    .cmd
    files
  • Automating Windows tasks (file operations, deployments, backups)
  • Building CLI tools intended for a
    bin/
    folder on PATH
  • Writing scheduled task scripts (SCHTASKS, Task Scheduler)
  • Debugging batch script issues (variable expansion, error levels, quoting)
  • Integrating batch scripts with external tools (curl, git, Node.js, Python)
  • Scaffolding new batch-based projects with structured templates
  • 创建或编辑
    .bat
    .cmd
    文件
  • 自动化Windows任务(文件操作、部署、备份)
  • 开发用于PATH中
    bin/
    目录的CLI工具
  • 编写计划任务脚本(SCHTASKS、任务计划程序)
  • 调试批处理脚本问题(变量展开、错误级别、引号处理)
  • 将批处理脚本与外部工具集成(curl、git、Node.js、Python)
  • 使用结构化模板搭建新的批处理项目

Prerequisites

前置条件

  • Windows NT-based OS (Windows 7 or later)
  • cmd.exe (built-in)
  • Optional: a
    bin/
    directory on PATH for distributing scripts as commands
  • Optional: PATHEXT configured to include
    .BAT;.CMD
    (default on Windows)
  • 基于Windows NT的操作系统(Windows 7或更高版本)
  • cmd.exe(系统内置)
  • 可选:PATH中的
    bin/
    目录,用于将脚本作为命令分发
  • 可选:PATHEXT配置为包含
    .BAT;.CMD
    (Windows默认已配置)

Command Interpretation

命令解析流程

cmd.exe processes each line through four stages in order:
  1. Variable substitution
    %VAR%
    tokens are replaced with environment variable values.
    %0
    %9
    reference batch arguments.
    %*
    expands to all arguments.
  2. Quoting and escaping — Caret
    ^
    escapes special characters (
    & | < > ^
    ). Quotation marks prevent interpretation of enclosed special characters. In batch files,
    %%
    yields a literal
    %
    .
  3. Syntax parsing — Lines are split into pipelines (
    |
    ), compound commands (
    &
    ,
    &&
    ,
    ||
    ), and parenthesized groups
    ( )
    .
  4. Redirection
    >
    overwrites,
    >>
    appends,
    <
    reads input,
    2>
    redirects stderr,
    2>&1
    merges stderr into stdout,
    >NUL
    discards output.
cmd.exe按以下四个阶段依次处理每一行命令:
  1. 变量替换
    %VAR%
    标记会被替换为环境变量的值。
    %0
    %9
    引用批处理参数。
    %*
    展开为所有参数。
  2. 引号与转义 — 脱字符
    ^
    用于转义特殊字符(
    & | < > ^
    )。引号可防止对包含的特殊字符进行解析。在批处理文件中,
    %%
    表示字面量
    %
  3. 语法解析 — 行被拆分为管道(
    |
    )、复合命令(
    &
    &&
    ||
    )和括号组
    ( )
  4. 重定向
    >
    覆盖文件内容,
    >>
    追加内容,
    <
    读取输入,
    2>
    重定向stderr,
    2>&1
    将stderr合并到stdout,
    >NUL
    丢弃输出。

Variables

变量

Environment Variables

环境变量

bat
set _MY_VAR=Hello World
echo %_MY_VAR%
set _MY_VAR=
  • set
    with no arguments lists all variables
  • set _PREFIX
    lists variables starting with
    _PREFIX
  • No spaces around
    =
    set name = val
    sets variable
    "name "
    to
    " val"
bat
set _MY_VAR=Hello World
echo %_MY_VAR%
set _MY_VAR=
  • 不带参数的
    set
    命令列出所有变量
  • set _PREFIX
    列出以
    _PREFIX
    开头的变量
  • =
    两侧不能有空格 —
    set name = val
    会将变量
    "name "
    设置为
    " val"

Special Variables

特殊变量

VariableValue
%CD%
Current directory
%DATE%
System date (locale-dependent)
%TIME%
System time HH:MM:SS.mm
%RANDOM%
Pseudorandom number 0–32767
%ERRORLEVEL%
Exit code of last command
%USERNAME%
Current user name
%USERPROFILE%
Current user profile path
%TEMP%
/
%TMP%
Temporary file directory
%PATHEXT%
Executable extensions list
%COMSPEC%
Path to cmd.exe
变量说明
%CD%
当前目录
%DATE%
系统日期(依赖区域设置)
%TIME%
系统时间 HH:MM:SS.mm
%RANDOM%
伪随机数 0–32767
%ERRORLEVEL%
上一条命令的退出码
%USERNAME%
当前用户名
%USERPROFILE%
当前用户配置文件路径
%TEMP%
/
%TMP%
临时文件目录
%PATHEXT%
可执行文件扩展名列表
%COMSPEC%
cmd.exe的路径

Scoping with SETLOCAL / ENDLOCAL

使用SETLOCAL / ENDLOCAL限定作用域

bat
setlocal
set _LOCAL_VAR=scoped value
endlocal
REM _LOCAL_VAR is no longer defined here
To return a value from a scoped block:
bat
endlocal & set _RESULT=%_LOCAL_VAR%
bat
setlocal
set _LOCAL_VAR=scoped value
endlocal
REM _LOCAL_VAR在此处不再定义
要从作用域块中返回值:
bat
endlocal & set _RESULT=%_LOCAL_VAR%

Delayed Expansion

延迟扩展

Variables inside parenthesized blocks are expanded at parse time. Use delayed expansion for runtime evaluation:
bat
setlocal EnableDelayedExpansion
set _COUNT=0
for /l %%i in (1,1,5) do (
    set /a _COUNT+=1
    echo !_COUNT!
)
endlocal
  • !VAR!
    expands at execution time (delayed)
  • %VAR%
    expands at parse time (immediate)
括号块内的变量会在解析时展开。使用延迟扩展可实现运行时求值:
bat
setlocal EnableDelayedExpansion
set _COUNT=0
for /l %%i in (1,1,5) do (
    set /a _COUNT+=1
    echo !_COUNT!
)
endlocal
  • !VAR!
    在执行时展开(延迟)
  • %VAR%
    在解析时展开(立即)

Control Flow

控制流

Conditional Execution

条件执行

bat
if exist "output.txt" echo File found
if not defined _MY_VAR echo Variable not set
if "%_STATUS%"=="ready" (echo Go) else (echo Wait)
if %ERRORLEVEL% neq 0 echo Command failed
Comparison operators:
equ
,
neq
,
lss
,
leq
,
gtr
,
geq
. Use
/i
for case-insensitive string comparison.
bat
if exist "output.txt" echo File found
if not defined _MY_VAR echo Variable not set
if "%_STATUS%"=="ready" (echo Go) else (echo Wait)
if %ERRORLEVEL% neq 0 echo Command failed
比较运算符:
equ
(等于)、
neq
(不等于)、
lss
(小于)、
leq
(小于等于)、
gtr
(大于)、
geq
(大于等于)。使用
/i
进行不区分大小写的字符串比较。

Compound Commands

复合命令

bat
command1 & command2        & REM Always run both
command1 && command2       & REM Run command2 only if command1 succeeds
command1 || command2       & REM Run command2 only if command1 fails
bat
command1 & command2        & REM 始终执行两条命令
command1 && command2       & REM 仅当command1成功时才执行command2
command1 || command2       & REM 仅当command1失败时才执行command2

FOR Loops

FOR循环

bat
REM Iterate over a set of values
for %%i in (alpha beta gamma) do echo %%i

REM Numeric range: start, step, end
for /l %%i in (1,1,10) do echo %%i

REM Files in a directory
for %%f in (*.txt) do echo %%f

REM Recursive file search
for /r %%f in (*.log) do echo %%f

REM Directories only
for /d %%d in (*) do echo %%d

REM Parse command output
for /f "tokens=1,2 delims=:" %%a in ('ipconfig ^| findstr "IPv4"') do echo %%b

REM Parse file lines
for /f "usebackq tokens=*" %%a in ("data.txt") do echo %%a
bat
REM 遍历一组值
for %%i in (alpha beta gamma) do echo %%i

REM 数值范围:起始值, 步长, 结束值
for /l %%i in (1,1,10) do echo %%i

REM 目录中的文件
for %%f in (*.txt) do echo %%f

REM 递归搜索文件
for /r %%f in (*.log) do echo %%f

REM 仅遍历目录
for /d %%d in (*) do echo %%d

REM 解析命令输出
for /f "tokens=1,2 delims=:" %%a in ('ipconfig ^| findstr "IPv4"') do echo %%b

REM 解析文件行
for /f "usebackq tokens=*" %%a in ("data.txt") do echo %%a

GOTO and Labels

GOTO与标签

bat
goto :main_logic
:usage
echo Usage: %~nx0 [options]
exit /b 1

:main_logic
echo Running main logic...
goto :eof
goto :eof
exits the current batch or subroutine. Labels start with
:
.
bat
goto :main_logic
:usage
echo Usage: %~nx0 [options]
exit /b 1

:main_logic
echo Running main logic...
goto :eof
goto :eof
退出当前批处理或子例程。标签以
:
开头。

Command-Line Arguments

命令行参数

SyntaxValue
%0
Script name as invoked
%1
%9
Positional arguments
%*
All arguments (unaffected by SHIFT)
%~1
Argument 1 with enclosing quotes removed
%~f1
Full path of argument 1
%~d1
Drive letter of argument 1
%~p1
Path (without drive) of argument 1
%~n1
File name (no extension) of argument 1
%~x1
Extension of argument 1
%~dp0
Drive and path of the batch file itself
%~nx0
File name with extension of the batch file
%~z1
File size of argument 1
%~$PATH:1
Search PATH for argument 1
语法说明
%0
调用时的脚本名称
%1
%9
位置参数
%*
所有参数(不受SHIFT影响)
%~1
移除引号后的参数1
%~f1
参数1的完整路径
%~d1
参数1的驱动器号
%~p1
参数1的路径(不含驱动器)
%~n1
参数1的文件名(不含扩展名)
%~x1
参数1的扩展名
%~dp0
批处理文件自身的驱动器和路径
%~nx0
批处理文件的文件名(含扩展名)
%~z1
参数1的文件大小
%~$PATH:1
在PATH中搜索参数1

Argument Parsing Pattern

参数解析示例

bat
:parse_args
if "%~1"=="" goto :args_done
if /i "%~1"=="--help" goto :usage
if /i "%~1"=="--output" (
    set "_OUTPUT_DIR=%~2"
    shift
)
shift
goto :parse_args
:args_done
bat
:parse_args
if "%~1"=="" goto :args_done
if /i "%~1"=="--help" goto :usage
if /i "%~1"=="--output" (
    set "_OUTPUT_DIR=%~2"
    shift
)
shift
goto :parse_args
:args_done

String Processing

字符串处理

Substrings

子字符串

bat
set _STR=Hello World
echo %_STR:~0,5%       & REM "Hello"
echo %_STR:~6%         & REM "World"
echo %_STR:~-5%        & REM "World"
echo %_STR:~0,-6%      & REM "Hello"
bat
set _STR=Hello World
echo %_STR:~0,5%       & REM "Hello"
echo %_STR:~6%         & REM "World"
echo %_STR:~-5%        & REM "World"
echo %_STR:~0,-6%      & REM "Hello"

Search and Replace

搜索与替换

bat
set _STR=Hello World
echo %_STR:World=Earth%       & REM "Hello Earth"
echo %_STR:Hello=%            & REM " World" (remove "Hello")
bat
set _STR=Hello World
echo %_STR:World=Earth%       & REM "Hello Earth"
echo %_STR:Hello=%            & REM " World"(移除"Hello")

Substring Containment Test

子字符串包含测试

bat
if not "%_STR:World=%"=="%_STR%" echo Contains "World"
bat
if not "%_STR:World=%"=="%_STR%" echo Contains "World"

Functions

函数

Functions use labels, CALL, and SETLOCAL/ENDLOCAL:
bat
@echo off
call :greet "Jane Doe"
echo Result: %_GREETING%
exit /b 0

:greet
setlocal
set "_MSG=Hello, %~1"
endlocal & set "_GREETING=%_MSG%"
exit /b 0
  • call :label args
    invokes a function
  • exit /b
    returns from the function (not the script)
  • Use the
    endlocal & set
    trick to pass values out of a scoped block
函数使用标签、CALL以及SETLOCAL/ENDLOCAL:
bat
@echo off
call :greet "Jane Doe"
echo Result: %_GREETING%
exit /b 0

:greet
setlocal
set "_MSG=Hello, %~1"
endlocal & set "_GREETING=%_MSG%"
exit /b 0
  • call :label args
    调用函数
  • exit /b
    从函数返回(而非退出脚本)
  • 使用
    endlocal & set
    技巧将值从作用域块中传出

Arithmetic

算术运算

set /a
performs 32-bit signed integer arithmetic:
bat
set /a _RESULT=10 * 5 + 3
set /a _COUNTER+=1
set /a _REMAINDER=14 %% 3       & REM Use %% for modulo in batch files
set /a _BITS="255 & 0x0F"       & REM Bitwise AND
Supported operators:
+ - * / %% ( )
and bitwise
& | ^ ~ << >>
.
Hexadecimal (
0xFF
) and octal (
077
) literals are supported.
set /a
执行32位有符号整数运算:
bat
set /a _RESULT=10 * 5 + 3
set /a _COUNTER+=1
set /a _REMAINDER=14 %% 3       & REM 在批处理文件中使用%%表示取模
set /a _BITS="255 & 0x0F"       & REM 按位与
支持的运算符:
+ - * / %% ( )
以及按位运算符
& | ^ ~ << >>
支持十六进制(
0xFF
)和八进制(
077
)字面量。

Error Handling

错误处理

Error Level Conventions

错误级别约定

  • 0
    = success
  • Non-zero = failure (typically
    1
    )
bat
mycommand.exe
if %ERRORLEVEL% neq 0 (
    echo ERROR: mycommand failed with code %ERRORLEVEL%
    exit /b %ERRORLEVEL%
)
  • 0
    = 成功
  • 非零 = 失败(通常为
    1
bat
mycommand.exe
if %ERRORLEVEL% neq 0 (
    echo ERROR: mycommand failed with code %ERRORLEVEL%
    exit /b %ERRORLEVEL%
)

Fail-Fast Pattern

快速失败模式

bat
command1 || (echo command1 failed & exit /b 1)
command2 || (echo command2 failed & exit /b 1)
bat
command1 || (echo command1 failed & exit /b 1)
command2 || (echo command2 failed & exit /b 1)

Setting Exit Codes

设置退出码

bat
exit /b 0        & REM Return success from a batch/function
exit /b 1        & REM Return failure
cmd /c "exit /b 42"   & REM Set ERRORLEVEL to 42 inline
bat
exit /b 0        & REM 从批处理/函数返回成功
exit /b 1        & REM 返回失败
cmd /c "exit /b 42"   & REM 内联设置ERRORLEVEL为42

Essential Commands Reference

核心命令参考

File Operations

文件操作

CommandPurpose
DIR
List directory contents
COPY
Copy files
XCOPY
Extended copy with subdirectories (legacy)
ROBOCOPY
Robust copy with retry, mirror, logging
MOVE
Move or rename files
DEL
Delete files
REN
Rename files
MD
/
MKDIR
Create directories
RD
/
RMDIR
Remove directories
MKLINK
Create symbolic or hard links
ATTRIB
View or set file attributes
TYPE
Print file contents
MORE
Paginated file display
TREE
Display directory structure
REPLACE
Replace files in destination with source
COMPACT
Show or set NTFS compression
EXPAND
Extract from .cab files
MAKECAB
Create .cab archives
TAR
Create or extract tar archives
命令用途
DIR
列出目录内容
COPY
复制文件
XCOPY
支持子目录的扩展复制(传统工具)
ROBOCOPY
具备重试、镜像、日志功能的可靠复制工具
MOVE
移动或重命名文件
DEL
删除文件
REN
重命名文件
MD
/
MKDIR
创建目录
RD
/
RMDIR
删除目录
MKLINK
创建符号链接或硬链接
ATTRIB
查看或设置文件属性
TYPE
打印文件内容
MORE
分页显示文件内容
TREE
显示目录结构
REPLACE
用源文件替换目标目录中的文件
COMPACT
查看或设置NTFS压缩
EXPAND
从.cab文件中提取内容
MAKECAB
创建.cab归档文件
TAR
创建或提取tar归档文件

Text Search and Processing

文本搜索与处理

CommandPurpose
FIND
Search for literal strings
FINDSTR
Search with limited regular expressions
SORT
Sort lines alphabetically
CLIP
Copy piped input to clipboard
FC
Compare two files
COMP
Binary file comparison
CERTUTIL
Encode/decode Base64, compute hashes
命令用途
FIND
搜索字面字符串
FINDSTR
使用有限正则表达式搜索
SORT
按字母顺序排序行
CLIP
将管道输入复制到剪贴板
FC
比较两个文件
COMP
二进制文件比较
CERTUTIL
Base64编码/解码、计算哈希值

System Information

系统信息

CommandPurpose
SYSTEMINFO
Full system configuration
HOSTNAME
Display computer name
VER
Windows version
WHOAMI
Current user and group info
TASKLIST
List running processes
TASKKILL
Terminate processes
WMIC
WMI queries (drives, OS, memory)
SC
Service control (query, start, stop)
DRIVERQUERY
List installed drivers
REG
Registry operations (query, add, delete)
SETX
Set persistent environment variables
命令用途
SYSTEMINFO
完整系统配置信息
HOSTNAME
显示计算机名称
VER
Windows版本
WHOAMI
当前用户和组信息
TASKLIST
列出运行中的进程
TASKKILL
终止进程
WMIC
WMI查询(驱动器、操作系统、内存等)
SC
服务控制(查询、启动、停止)
DRIVERQUERY
列出已安装的驱动程序
REG
注册表操作(查询、添加、删除)
SETX
设置持久化环境变量

Network

网络

CommandPurpose
PING
Test network connectivity
IPCONFIG
IP configuration
NSLOOKUP
DNS lookup
NETSTAT
Network connections and ports
TRACERT
Trace route to host
NET USE
Map/disconnect network drives
NET USER
Manage user accounts
NETSH
Network configuration utility
ARP
ARP cache management
ROUTE
Routing table management
CURL
HTTP requests (Windows 10+)
SSH
Secure shell (Windows 10+)
命令用途
PING
测试网络连通性
IPCONFIG
IP配置信息
NSLOOKUP
DNS查询
NETSTAT
网络连接和端口信息
TRACERT
追踪到主机的路由
NET USE
映射/断开网络驱动器
NET USER
管理用户账户
NETSH
网络配置工具
ARP
ARP缓存管理
ROUTE
路由表管理
CURL
HTTP请求(Windows 10+)
SSH
安全Shell(Windows 10+)

Scheduling and Automation

计划任务与自动化

CommandPurpose
SCHTASKS
Create and manage scheduled tasks
TIMEOUT
Wait N seconds (Vista+)
START
Launch programs asynchronously
RUNAS
Run as different user
SHUTDOWN
Shutdown or restart
FORFILES
Find files by date and execute commands
命令用途
SCHTASKS
创建和管理计划任务
TIMEOUT
等待N秒(Vista+)
START
异步启动程序
RUNAS
以其他用户身份运行
SHUTDOWN
关机或重启
FORFILES
按日期查找文件并执行命令

Shell Utilities

Shell工具

CommandPurpose
WHERE
Locate executables in PATH
DOSKEY
Create command macros
CHOICE
Prompt for single-key input
MODE
Configure console size and ports
SUBST
Map folder to drive letter
CHCP
Get or set console code page
COLOR
Set console colors
TITLE
Set console window title
ASSOC
/
FTYPE
File type associations
命令用途
WHERE
在PATH中查找可执行文件
DOSKEY
创建命令宏
CHOICE
提示单键输入
MODE
配置控制台大小和端口
SUBST
将文件夹映射为驱动器号
CHCP
获取或设置控制台代码页
COLOR
设置控制台颜色
TITLE
设置控制台窗口标题
ASSOC
/
FTYPE
文件类型关联

Shell Syntax and Expressions

Shell语法与表达式

Parentheses for Grouping

括号分组

Parentheses turn compound commands into a single unit for redirection or conditional execution:
bat
(echo Line 1 & echo Line 2) > output.txt
if exist "data.csv" (
    echo Processing...
    call :process "data.csv"
) else (
    echo No data found.
)
括号将复合命令转换为单个单元,用于重定向或条件执行:
bat
(echo Line 1 & echo Line 2) > output.txt
if exist "data.csv" (
    echo Processing...
    call :process "data.csv"
) else (
    echo No data found.
)

Escape Characters

转义字符

The caret
^
escapes the next character:
bat
echo Total ^& Summary          & REM Outputs: Total & Summary
echo 100%% complete            & REM Outputs: 100% complete (in batch)
echo Line one^
Line two                       & REM Caret escapes the newline
After a pipe, triple caret is needed:
echo x ^^^& y | findstr x
脱字符
^
用于转义下一个字符:
bat
echo Total ^& Summary          & REM 输出:Total & Summary
echo 100%% complete            & REM 输出:100% complete(批处理文件中)
echo Line one^
Line two                       & REM 脱字符转义换行符
管道后需要使用三重脱字符:
echo x ^^^& y | findstr x

Wildcards

通配符

  • *
    matches any sequence of characters
  • ?
    matches a single character (or zero at end of period-free segment)
bat
dir *.txt           & REM All .txt files
ren *.jpeg *.jpg    & REM Bulk rename
  • *
    匹配任意字符序列
  • ?
    匹配单个字符(或在无句点的段末尾匹配零个字符)
bat
dir *.txt           & REM 所有.txt文件
ren *.jpeg *.jpg    & REM 批量重命名

Redirection Summary

重定向汇总

bat
command > file.txt          & REM Overwrite stdout to file
command >> file.txt         & REM Append stdout to file
command 2> errors.log       & REM Redirect stderr
command > all.log 2>&1      & REM Merge stderr into stdout
command < input.txt         & REM Read stdin from file
command > NUL 2>&1          & REM Discard all output
bat
command > file.txt          & REM 将stdout覆盖写入文件
command >> file.txt         & REM 将stdout追加写入文件
command 2> errors.log       & REM 重定向stderr
command > all.log 2>&1      & REM 将stderr合并到stdout
command < input.txt         & REM 从文件读取stdin
command > NUL 2>&1          & REM 丢弃所有输出

Writing Production-Quality Batch Files

编写生产级批处理文件

Standard Script Structure

标准脚本结构

bat
@echo off
setlocal EnableDelayedExpansion

REM ============================================================
REM  Script: example.bat
REM  Purpose: Describe what this script does
REM ============================================================

call :main %*
exit /b %ERRORLEVEL%

:main
    call :parse_args %*
    if not defined _TARGET (
        echo ERROR: --target is required. 1>&2
        call :usage
        exit /b 1
    )
    echo Processing: %_TARGET%
    exit /b 0

:parse_args
    if "%~1"=="" exit /b 0
    if /i "%~1"=="--target" set "_TARGET=%~2" & shift
    if /i "%~1"=="--help"   call :usage & exit /b 0
    shift
    goto :parse_args

:usage
    echo Usage: %~nx0 --target ^<path^> [--help]
    echo.
    echo Options:
    echo   --target   Path to process (required)
    echo   --help     Show this help message
    exit /b 0
bat
@echo off
setlocal EnableDelayedExpansion

REM ============================================================
REM  Script: example.bat
REM  Purpose: Describe what this script does
REM ============================================================

call :main %*
exit /b %ERRORLEVEL%

:main
    call :parse_args %*
    if not defined _TARGET (
        echo ERROR: --target is required. 1>&2
        call :usage
        exit /b 1
    )
    echo Processing: %_TARGET%
    exit /b 0

:parse_args
    if "%~1"=="" exit /b 0
    if /i "%~1"=="--target" set "_TARGET=%~2" & shift
    if /i "%~1"=="--help"   call :usage & exit /b 0
    shift
    goto :parse_args

:usage
    echo Usage: %~nx0 --target ^<path^> [--help]
    echo.
    echo Options:
    echo   --target   Path to process (required)
    echo   --help     Show this help message
    exit /b 0

Best Practices

最佳实践

  1. Always start with
    @echo off
    and
    setlocal
    — Prevents noisy output and variable leakage to the caller.
  2. Validate inputs before processing — Check required arguments and file existence early. Use
    if not defined
    and
    if not exist
    .
  3. Quote paths and variables — Use
    "%~1"
    and
    "%_MY_PATH%"
    to handle spaces and special characters safely.
  4. Use
    exit /b
    instead of
    exit
    — Avoids closing the parent console window.
  5. Return meaningful exit codes
    exit /b 0
    for success, non-zero for specific failures.
  6. Use
    %~dp0
    for script-relative paths
    — Ensures the script works regardless of the caller's working directory.
  7. Prefer
    ROBOCOPY
    over
    XCOPY
    — More reliable, supports retry, mirroring, and logging.
  8. Use
    EnableDelayedExpansion
    when modifying variables inside loops or parenthesized blocks.
  9. Write errors to stderr
    echo ERROR: message 1>&2
    keeps stdout clean for piping.
  10. Use
    REM
    for comments
    ::
    can cause issues inside
    FOR
    loop bodies.
  1. 始终以
    @echo off
    setlocal
    开头
    — 避免冗余输出,防止变量泄漏到调用者环境。
  2. 处理前验证输入 — 提前检查必填参数和文件是否存在。使用
    if not defined
    if not exist
  3. 为路径和变量添加引号 — 使用
    "%~1"
    "%_MY_PATH%"
    安全处理包含空格和特殊字符的路径。
  4. 使用
    exit /b
    而非
    exit
    — 避免关闭父控制台窗口。
  5. 返回有意义的退出码
    exit /b 0
    表示成功,非零值表示特定失败。
  6. 使用
    %~dp0
    获取脚本相对路径
    — 确保脚本无论调用者的工作目录如何都能正常运行。
  7. 优先使用
    ROBOCOPY
    而非
    XCOPY
    — 更可靠,支持重试、镜像和日志功能。
  8. 在循环或括号块内修改变量时,启用
    EnableDelayedExpansion
  9. 将错误信息写入stderr
    echo ERROR: message 1>&2
    保持stdout干净,便于管道操作。
  10. 使用
    REM
    添加注释
    — 在FOR循环体中使用
    ::
    可能会导致问题。

Security Considerations

安全注意事项

  • Never store credentials in batch files — Use environment variables, credential stores, or prompts.
  • Validate user input — Unquoted variables containing
    &
    ,
    |
    , or
    >
    can inject commands. Always quote:
    "%_USER_INPUT%"
    .
  • Use
    SETLOCAL
    — Prevents variable values from leaking to parent processes.
  • Sanitize file paths — Validate paths before passing to
    DEL
    ,
    RD
    , or
    ROBOCOPY
    to prevent unintended deletion.
  • Avoid
    SET /P
    for sensitive input
    — Input is visible and stored in console history. Use a dedicated credential tool when possible.
  • 切勿在批处理文件中存储凭据 — 使用环境变量、凭据存储或提示输入。
  • 验证用户输入 — 未加引号的变量若包含
    &
    |
    >
    可能会注入命令。始终添加引号:
    "%_USER_INPUT%"
  • 使用
    SETLOCAL
    — 防止变量值泄漏到父进程。
  • 清理文件路径 — 在传递给
    DEL
    RD
    ROBOCOPY
    之前验证路径,防止意外删除。
  • 避免使用
    SET /P
    输入敏感信息
    — 输入内容可见并存储在控制台历史记录中。尽可能使用专用凭据工具。

Debugging and Troubleshooting

调试与故障排除

TechniqueHow
Trace executionRemove
@echo off
or use
@echo on
temporarily
Step throughAdd
PAUSE
between sections
Check error level
echo Exit code: %ERRORLEVEL%
after each command
Inspect variables
set _MY_
to list all variables starting with
_MY_
Delayed expansion issuesVariable inside
( )
block not updating? Enable
!VAR!
syntax
FOR loop
%%
vs
%
Use
%%i
in batch files,
%i
on the command line
Spaces in SET
set name=value
not
set name = value
Caret in pipesAfter a pipe, use
^^^
to escape special chars
Parentheses in SET /AEscape with
^(
and
^)
inside
if
blocks, or use quotes
Double percent for modulo
set /a r=14 %% 3
in batch files
技巧操作方法
跟踪执行过程临时移除
@echo off
或使用
@echo on
逐步执行在各部分之间添加
PAUSE
检查错误级别每条命令后执行
echo Exit code: %ERRORLEVEL%
检查变量使用
set _MY_
列出所有以
_MY_
开头的变量
延迟扩展问题括号块内的变量未更新?启用
!VAR!
语法
FOR循环中的
%%
%
批处理文件中使用
%%i
,命令行中使用
%i
SET命令中的空格使用
set name=value
而非
set name = value
管道中的脱字符管道后使用
^^^
转义特殊字符
SET /A中的括号在if块内使用
^(
^)
转义,或使用引号
取模使用双百分号批处理文件中使用
set /a r=14 %% 3

Cross-Platform and Extended Tools

跨平台与扩展工具

When batch scripting reaches its limits, these tools extend cmd.exe capabilities:
ToolPurpose
CygwinFull POSIX environment on Windows (grep, sed, awk, ssh)
MSYS2Lightweight Unix tools and package manager (pacman)
WSLWindows Subsystem for Linux — run native Linux binaries
GnuWin32Individual GNU utilities as native Windows executables
PowerShellModern Windows scripting with .NET integration
Use batch when you need: fast startup, simple file operations, PATH-based CLI tools, or Task Scheduler integration. Consider PowerShell or WSL for complex data processing, REST APIs, or object-oriented scripting.
当批处理脚本达到其局限性时,以下工具可扩展cmd.exe的功能:
工具用途
CygwinWindows上的完整POSIX环境(grep、sed、awk、ssh)
MSYS2轻量级Unix工具和包管理器(pacman)
WSLWindows Subsystem for Linux — 运行原生Linux二进制文件
GnuWin32作为原生Windows可执行文件的单个GNU工具
PowerShell集成.NET的现代Windows脚本工具
当你需要以下场景时使用批处理:快速启动、简单文件操作、基于PATH的CLI工具、或任务计划程序集成。对于复杂数据处理、REST API或面向对象脚本,考虑使用PowerShell或WSL。

CMD Keyboard Shortcuts

CMD键盘快捷键

ShortcutAction
Tab
Auto-complete file/folder names
Up
/
Down
Navigate command history
F7
Show command history popup
F3
Repeat last command
Esc
Clear current line
Ctrl+C
Cancel running command
Alt+F7
Clear command history
快捷键操作
Tab
自动补全文件/文件夹名称
Up
/
Down
浏览命令历史
F7
显示命令历史弹窗
F3
重复上一条命令
Esc
清除当前行
Ctrl+C
取消正在运行的命令
Alt+F7
清除命令历史

Reference Files

参考文件

The
references/
folder contains detailed documentation:
FileContents
tools-and-resources.md
Windows tools, utilities, package managers, terminals
batch-files-and-functions.md
Example scripts, techniques, best practices links
windows-commands.md
Comprehensive A-Z Windows command reference
cygwin.md
Cygwin user guide and FAQ
msys2.md
MSYS2 installation, packages, and environments
windows-subsystem-on-linux.md
WSL setup, commands, and documentation
references/
文件夹包含详细文档:
文件内容
tools-and-resources.md
Windows工具、实用程序、包管理器、终端
batch-files-and-functions.md
示例脚本、技巧、最佳实践链接
windows-commands.md
全面的A-Z Windows命令参考
cygwin.md
Cygwin用户指南和常见问题
msys2.md
MSYS2安装、包和环境配置
windows-subsystem-on-linux.md
WSL设置、命令和文档

Asset Templates

资产模板

The
assets/
folder contains starter batch file template data, but as text files:
TemplatePurpose
executable.txt
Standalone CLI tool with argument parsing
library.txt
Reusable function library with CALL-able labels
task.txt
Scheduled task / automation script
assets/
文件夹包含批处理文件模板的初始数据,以文本文件形式存储:
模板用途
executable.txt
带参数解析的独立CLI工具
library.txt
可通过CALL调用标签的可重用函数库
task.txt
计划任务/自动化脚本