batch-files
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseBatch 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 or
.batfiles.cmd - Automating Windows tasks (file operations, deployments, backups)
- Building CLI tools intended for a folder on PATH
bin/ - 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中目录的CLI工具
bin/ - 编写计划任务脚本(SCHTASKS、任务计划程序)
- 调试批处理脚本问题(变量展开、错误级别、引号处理)
- 将批处理脚本与外部工具集成(curl、git、Node.js、Python)
- 使用结构化模板搭建新的批处理项目
Prerequisites
前置条件
- Windows NT-based OS (Windows 7 or later)
- cmd.exe (built-in)
- Optional: a directory on PATH for distributing scripts as commands
bin/ - Optional: PATHEXT configured to include (default on Windows)
.BAT;.CMD
- 基于Windows NT的操作系统(Windows 7或更高版本)
- cmd.exe(系统内置)
- 可选:PATH中的目录,用于将脚本作为命令分发
bin/ - 可选:PATHEXT配置为包含(Windows默认已配置)
.BAT;.CMD
Command Interpretation
命令解析流程
cmd.exe processes each line through four stages in order:
- Variable substitution — tokens are replaced with environment variable values.
%VAR%–%0reference batch arguments.%9expands to all arguments.%* - Quoting and escaping — Caret escapes special characters (
^). Quotation marks prevent interpretation of enclosed special characters. In batch files,& | < > ^yields a literal%%.% - Syntax parsing — Lines are split into pipelines (), compound commands (
|,&,&&), and parenthesized groups||.( ) - Redirection — overwrites,
>appends,>>reads input,<redirects stderr,2>merges stderr into stdout,2>&1discards output.>NUL
cmd.exe按以下四个阶段依次处理每一行命令:
- 变量替换 — 标记会被替换为环境变量的值。
%VAR%–%0引用批处理参数。%9展开为所有参数。%* - 引号与转义 — 脱字符用于转义特殊字符(
^)。引号可防止对包含的特殊字符进行解析。在批处理文件中,& | < > ^表示字面量%%。% - 语法解析 — 行被拆分为管道()、复合命令(
|、&、&&)和括号组||。( ) - 重定向 — 覆盖文件内容,
>追加内容,>>读取输入,<重定向stderr,2>将stderr合并到stdout,2>&1丢弃输出。>NUL
Variables
变量
Environment Variables
环境变量
bat
set _MY_VAR=Hello World
echo %_MY_VAR%
set _MY_VAR=- with no arguments lists all variables
set - lists variables starting with
set _PREFIX_PREFIX - No spaces around —
=sets variableset name = valto"name "" val"
bat
set _MY_VAR=Hello World
echo %_MY_VAR%
set _MY_VAR=- 不带参数的命令列出所有变量
set - 列出以
set _PREFIX开头的变量_PREFIX - 两侧不能有空格 —
=会将变量set name = val设置为"name "" val"
Special Variables
特殊变量
| Variable | Value |
|---|---|
| Current directory |
| System date (locale-dependent) |
| System time HH:MM:SS.mm |
| Pseudorandom number 0–32767 |
| Exit code of last command |
| Current user name |
| Current user profile path |
| Temporary file directory |
| Executable extensions list |
| Path to cmd.exe |
| 变量 | 说明 |
|---|---|
| 当前目录 |
| 系统日期(依赖区域设置) |
| 系统时间 HH:MM:SS.mm |
| 伪随机数 0–32767 |
| 上一条命令的退出码 |
| 当前用户名 |
| 当前用户配置文件路径 |
| 临时文件目录 |
| 可执行文件扩展名列表 |
| cmd.exe的路径 |
Scoping with SETLOCAL / ENDLOCAL
使用SETLOCAL / ENDLOCAL限定作用域
bat
setlocal
set _LOCAL_VAR=scoped value
endlocal
REM _LOCAL_VAR is no longer defined hereTo 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- expands at execution time (delayed)
!VAR! - expands at parse time (immediate)
%VAR%
括号块内的变量会在解析时展开。使用延迟扩展可实现运行时求值:
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 failedComparison operators: , , , , , . Use for case-insensitive string comparison.
equneqlssleqgtrgeq/ibat
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比较运算符:(等于)、(不等于)、(小于)、(小于等于)、(大于)、(大于等于)。使用进行不区分大小写的字符串比较。
equneqlssleqgtrgeq/iCompound 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 failsbat
command1 & command2 & REM 始终执行两条命令
command1 && command2 & REM 仅当command1成功时才执行command2
command1 || command2 & REM 仅当command1失败时才执行command2FOR 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 %%abat
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 %%aGOTO and Labels
GOTO与标签
bat
goto :main_logic
:usage
echo Usage: %~nx0 [options]
exit /b 1
:main_logic
echo Running main logic...
goto :eofgoto :eof:bat
goto :main_logic
:usage
echo Usage: %~nx0 [options]
exit /b 1
:main_logic
echo Running main logic...
goto :eofgoto :eof:Command-Line Arguments
命令行参数
| Syntax | Value |
|---|---|
| Script name as invoked |
| Positional arguments |
| All arguments (unaffected by SHIFT) |
| Argument 1 with enclosing quotes removed |
| Full path of argument 1 |
| Drive letter of argument 1 |
| Path (without drive) of argument 1 |
| File name (no extension) of argument 1 |
| Extension of argument 1 |
| Drive and path of the batch file itself |
| File name with extension of the batch file |
| File size of argument 1 |
| Search PATH for argument 1 |
| 语法 | 说明 |
|---|---|
| 调用时的脚本名称 |
| 位置参数 |
| 所有参数(不受SHIFT影响) |
| 移除引号后的参数1 |
| 参数1的完整路径 |
| 参数1的驱动器号 |
| 参数1的路径(不含驱动器) |
| 参数1的文件名(不含扩展名) |
| 参数1的扩展名 |
| 批处理文件自身的驱动器和路径 |
| 批处理文件的文件名(含扩展名) |
| 参数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_donebat
: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_doneString 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- invokes a function
call :label args - returns from the function (not the script)
exit /b - Use the trick to pass values out of a scoped block
endlocal & set
函数使用标签、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 /abat
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 ANDSupported operators: and bitwise .
+ - * / %% ( )& | ^ ~ << >>Hexadecimal () and octal () literals are supported.
0xFF077set /abat
set /a _RESULT=10 * 5 + 3
set /a _COUNTER+=1
set /a _REMAINDER=14 %% 3 & REM 在批处理文件中使用%%表示取模
set /a _BITS="255 & 0x0F" & REM 按位与支持的运算符:以及按位运算符。
+ - * / %% ( )& | ^ ~ << >>支持十六进制()和八进制()字面量。
0xFF077Error Handling
错误处理
Error Level Conventions
错误级别约定
- = success
0 - 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 inlinebat
exit /b 0 & REM 从批处理/函数返回成功
exit /b 1 & REM 返回失败
cmd /c "exit /b 42" & REM 内联设置ERRORLEVEL为42Essential Commands Reference
核心命令参考
File Operations
文件操作
| Command | Purpose |
|---|---|
| List directory contents |
| Copy files |
| Extended copy with subdirectories (legacy) |
| Robust copy with retry, mirror, logging |
| Move or rename files |
| Delete files |
| Rename files |
| Create directories |
| Remove directories |
| Create symbolic or hard links |
| View or set file attributes |
| Print file contents |
| Paginated file display |
| Display directory structure |
| Replace files in destination with source |
| Show or set NTFS compression |
| Extract from .cab files |
| Create .cab archives |
| Create or extract tar archives |
| 命令 | 用途 |
|---|---|
| 列出目录内容 |
| 复制文件 |
| 支持子目录的扩展复制(传统工具) |
| 具备重试、镜像、日志功能的可靠复制工具 |
| 移动或重命名文件 |
| 删除文件 |
| 重命名文件 |
| 创建目录 |
| 删除目录 |
| 创建符号链接或硬链接 |
| 查看或设置文件属性 |
| 打印文件内容 |
| 分页显示文件内容 |
| 显示目录结构 |
| 用源文件替换目标目录中的文件 |
| 查看或设置NTFS压缩 |
| 从.cab文件中提取内容 |
| 创建.cab归档文件 |
| 创建或提取tar归档文件 |
Text Search and Processing
文本搜索与处理
| Command | Purpose |
|---|---|
| Search for literal strings |
| Search with limited regular expressions |
| Sort lines alphabetically |
| Copy piped input to clipboard |
| Compare two files |
| Binary file comparison |
| Encode/decode Base64, compute hashes |
| 命令 | 用途 |
|---|---|
| 搜索字面字符串 |
| 使用有限正则表达式搜索 |
| 按字母顺序排序行 |
| 将管道输入复制到剪贴板 |
| 比较两个文件 |
| 二进制文件比较 |
| Base64编码/解码、计算哈希值 |
System Information
系统信息
| Command | Purpose |
|---|---|
| Full system configuration |
| Display computer name |
| Windows version |
| Current user and group info |
| List running processes |
| Terminate processes |
| WMI queries (drives, OS, memory) |
| Service control (query, start, stop) |
| List installed drivers |
| Registry operations (query, add, delete) |
| Set persistent environment variables |
| 命令 | 用途 |
|---|---|
| 完整系统配置信息 |
| 显示计算机名称 |
| Windows版本 |
| 当前用户和组信息 |
| 列出运行中的进程 |
| 终止进程 |
| WMI查询(驱动器、操作系统、内存等) |
| 服务控制(查询、启动、停止) |
| 列出已安装的驱动程序 |
| 注册表操作(查询、添加、删除) |
| 设置持久化环境变量 |
Network
网络
| Command | Purpose |
|---|---|
| Test network connectivity |
| IP configuration |
| DNS lookup |
| Network connections and ports |
| Trace route to host |
| Map/disconnect network drives |
| Manage user accounts |
| Network configuration utility |
| ARP cache management |
| Routing table management |
| HTTP requests (Windows 10+) |
| Secure shell (Windows 10+) |
| 命令 | 用途 |
|---|---|
| 测试网络连通性 |
| IP配置信息 |
| DNS查询 |
| 网络连接和端口信息 |
| 追踪到主机的路由 |
| 映射/断开网络驱动器 |
| 管理用户账户 |
| 网络配置工具 |
| ARP缓存管理 |
| 路由表管理 |
| HTTP请求(Windows 10+) |
| 安全Shell(Windows 10+) |
Scheduling and Automation
计划任务与自动化
| Command | Purpose |
|---|---|
| Create and manage scheduled tasks |
| Wait N seconds (Vista+) |
| Launch programs asynchronously |
| Run as different user |
| Shutdown or restart |
| Find files by date and execute commands |
| 命令 | 用途 |
|---|---|
| 创建和管理计划任务 |
| 等待N秒(Vista+) |
| 异步启动程序 |
| 以其他用户身份运行 |
| 关机或重启 |
| 按日期查找文件并执行命令 |
Shell Utilities
Shell工具
| Command | Purpose |
|---|---|
| Locate executables in PATH |
| Create command macros |
| Prompt for single-key input |
| Configure console size and ports |
| Map folder to drive letter |
| Get or set console code page |
| Set console colors |
| Set console window title |
| File type associations |
| 命令 | 用途 |
|---|---|
| 在PATH中查找可执行文件 |
| 创建命令宏 |
| 提示单键输入 |
| 配置控制台大小和端口 |
| 将文件夹映射为驱动器号 |
| 获取或设置控制台代码页 |
| 设置控制台颜色 |
| 设置控制台窗口标题 |
| 文件类型关联 |
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 newlineAfter 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 xWildcards
通配符
- 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 outputbat
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 0bat
@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 0Best Practices
最佳实践
- Always start with and
@echo off— Prevents noisy output and variable leakage to the caller.setlocal - Validate inputs before processing — Check required arguments and file existence early. Use and
if not defined.if not exist - Quote paths and variables — Use and
"%~1"to handle spaces and special characters safely."%_MY_PATH%" - Use instead of
exit /b— Avoids closing the parent console window.exit - Return meaningful exit codes — for success, non-zero for specific failures.
exit /b 0 - Use for script-relative paths — Ensures the script works regardless of the caller's working directory.
%~dp0 - Prefer over
ROBOCOPY— More reliable, supports retry, mirroring, and logging.XCOPY - Use when modifying variables inside loops or parenthesized blocks.
EnableDelayedExpansion - Write errors to stderr — keeps stdout clean for piping.
echo ERROR: message 1>&2 - Use for comments —
REMcan cause issues inside::loop bodies.FOR
- 始终以和
@echo off开头 — 避免冗余输出,防止变量泄漏到调用者环境。setlocal - 处理前验证输入 — 提前检查必填参数和文件是否存在。使用和
if not defined。if not exist - 为路径和变量添加引号 — 使用和
"%~1"安全处理包含空格和特殊字符的路径。"%_MY_PATH%" - 使用而非
exit /b— 避免关闭父控制台窗口。exit - 返回有意义的退出码 — 表示成功,非零值表示特定失败。
exit /b 0 - 使用获取脚本相对路径 — 确保脚本无论调用者的工作目录如何都能正常运行。
%~dp0 - 优先使用而非
ROBOCOPY— 更可靠,支持重试、镜像和日志功能。XCOPY - 在循环或括号块内修改变量时,启用。
EnableDelayedExpansion - 将错误信息写入stderr — 保持stdout干净,便于管道操作。
echo ERROR: message 1>&2 - 使用添加注释 — 在FOR循环体中使用
REM可能会导致问题。::
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 — Prevents variable values from leaking to parent processes.
SETLOCAL - Sanitize file paths — Validate paths before passing to ,
DEL, orRDto prevent unintended deletion.ROBOCOPY - Avoid for sensitive input — Input is visible and stored in console history. Use a dedicated credential tool when possible.
SET /P
- 切勿在批处理文件中存储凭据 — 使用环境变量、凭据存储或提示输入。
- 验证用户输入 — 未加引号的变量若包含、
&或|可能会注入命令。始终添加引号:>。"%_USER_INPUT%" - 使用— 防止变量值泄漏到父进程。
SETLOCAL - 清理文件路径 — 在传递给、
DEL或RD之前验证路径,防止意外删除。ROBOCOPY - 避免使用输入敏感信息 — 输入内容可见并存储在控制台历史记录中。尽可能使用专用凭据工具。
SET /P
Debugging and Troubleshooting
调试与故障排除
| Technique | How |
|---|---|
| Trace execution | Remove |
| Step through | Add |
| Check error level | |
| Inspect variables | |
| Delayed expansion issues | Variable inside |
FOR loop | Use |
| Spaces in SET | |
| Caret in pipes | After a pipe, use |
| Parentheses in SET /A | Escape with |
| Double percent for modulo | |
| 技巧 | 操作方法 |
|---|---|
| 跟踪执行过程 | 临时移除 |
| 逐步执行 | 在各部分之间添加 |
| 检查错误级别 | 每条命令后执行 |
| 检查变量 | 使用 |
| 延迟扩展问题 | 括号块内的变量未更新?启用 |
FOR循环中的 | 批处理文件中使用 |
| SET命令中的空格 | 使用 |
| 管道中的脱字符 | 管道后使用 |
| SET /A中的括号 | 在if块内使用 |
| 取模使用双百分号 | 批处理文件中使用 |
Cross-Platform and Extended Tools
跨平台与扩展工具
When batch scripting reaches its limits, these tools extend cmd.exe capabilities:
| Tool | Purpose |
|---|---|
| Cygwin | Full POSIX environment on Windows (grep, sed, awk, ssh) |
| MSYS2 | Lightweight Unix tools and package manager (pacman) |
| WSL | Windows Subsystem for Linux — run native Linux binaries |
| GnuWin32 | Individual GNU utilities as native Windows executables |
| PowerShell | Modern 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的功能:
| 工具 | 用途 |
|---|---|
| Cygwin | Windows上的完整POSIX环境(grep、sed、awk、ssh) |
| MSYS2 | 轻量级Unix工具和包管理器(pacman) |
| WSL | Windows Subsystem for Linux — 运行原生Linux二进制文件 |
| GnuWin32 | 作为原生Windows可执行文件的单个GNU工具 |
| PowerShell | 集成.NET的现代Windows脚本工具 |
当你需要以下场景时使用批处理:快速启动、简单文件操作、基于PATH的CLI工具、或任务计划程序集成。对于复杂数据处理、REST API或面向对象脚本,考虑使用PowerShell或WSL。
CMD Keyboard Shortcuts
CMD键盘快捷键
| Shortcut | Action |
|---|---|
| Auto-complete file/folder names |
| Navigate command history |
| Show command history popup |
| Repeat last command |
| Clear current line |
| Cancel running command |
| Clear command history |
| 快捷键 | 操作 |
|---|---|
| 自动补全文件/文件夹名称 |
| 浏览命令历史 |
| 显示命令历史弹窗 |
| 重复上一条命令 |
| 清除当前行 |
| 取消正在运行的命令 |
| 清除命令历史 |
Reference Files
参考文件
The folder contains detailed documentation:
references/| File | Contents |
|---|---|
| Windows tools, utilities, package managers, terminals |
| Example scripts, techniques, best practices links |
| Comprehensive A-Z Windows command reference |
| Cygwin user guide and FAQ |
| MSYS2 installation, packages, and environments |
| WSL setup, commands, and documentation |
references/| 文件 | 内容 |
|---|---|
| Windows工具、实用程序、包管理器、终端 |
| 示例脚本、技巧、最佳实践链接 |
| 全面的A-Z Windows命令参考 |
| Cygwin用户指南和常见问题 |
| MSYS2安装、包和环境配置 |
| WSL设置、命令和文档 |
Asset Templates
资产模板
The folder contains starter batch file template data, but as text files:
assets/| Template | Purpose |
|---|---|
| Standalone CLI tool with argument parsing |
| Reusable function library with CALL-able labels |
| Scheduled task / automation script |
assets/| 模板 | 用途 |
|---|---|
| 带参数解析的独立CLI工具 |
| 可通过CALL调用标签的可重用函数库 |
| 计划任务/自动化脚本 |