Token导航 LogoToken导航TokenDH.com
研究检索敏感数据github未标认证来源可访问许可证需确认审计提醒

batch-files批处理文件

Agent Skill

用于围绕 GitHub 仓库、Issue、Pull Request、分支、提交和代码协作流程提供辅助能力。它适合让 Agent 查询项目状态、整理变更、辅助创建或检查协作事项,并把仓库中的信息转成可执行的下一步。使用时需要区分只读查询和写入操作;涉及创建 PR、修改 Issue、推送分支或访问私有仓库时,应确认 token 权限、目标仓库范围和用户授权。

总安装

269

周安装

11

GitHub Stars

31,691

下载量

86
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:batch-files(批处理文件)
来源仓库:https://github.com/github/awesome-copilot
仓库路径:skills/batch-files
安装命令:
npx skills add https://github.com/github/awesome-copilot --skill batch-files
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/github/awesome-copilot --skill batch-files

简介

用于批处理文件的创建与管理,支持自动化脚本执行与系统操作。

  • 适用于批量处理文件操作、简化重复性任务流程。
  • 通过 npx skills add 从 awesome-copilot 仓库安装,需具备文件系统访问权限。
  • 执行系统级操作时注意路径安全与用户权限匹配。
  • batch-files 属于研究检索类 Skill,可作为该场景下的辅助能力补充。

SKILL.md

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.

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

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)

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.

Variables

Environment Variables

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"

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

Scoping with SETLOCAL / ENDLOCAL

setlocal
set _LOCAL_VAR=scoped value
endlocal
REM _LOCAL_VAR is no longer defined here

To return a value from a scoped block:

endlocal & set _RESULT=%_LOCAL_VAR%

Delayed Expansion

Variables inside parenthesized blocks are expanded at parse time. Use delayed expansion for runtime evaluation:

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)

Control Flow

Conditional Execution

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.

Compound Commands

command1 & command2        & REM Always run both
command1 && command2       & REM Run command2 only if command1 succeeds
command1 || command2       & REM Run command2 only if command1 fails

FOR Loops

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

GOTO and Labels

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 :.

Command-Line Arguments

SyntaxValue
%0Script name as invoked
%1%9Positional arguments
%*All arguments (unaffected by SHIFT)
%~1Argument 1 with enclosing quotes removed
%~f1Full path of argument 1
%~d1Drive letter of argument 1
%~p1Path (without drive) of argument 1
%~n1File name (no extension) of argument 1
%~x1Extension of argument 1
%~dp0Drive and path of the batch file itself
%~nx0File name with extension of the batch file
%~z1File size of argument 1
%~$PATH:1Search PATH for argument 1

Argument Parsing Pattern

: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

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

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

Substring Containment Test

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

Functions

Functions use labels, CALL, and SETLOCAL/ENDLOCAL:

@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

Arithmetic

set /a performs 32-bit signed integer arithmetic:

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.

Error Handling

Error Level Conventions

  • 0 = success
  • Non-zero = failure (typically 1)
mycommand.exe
if %ERRORLEVEL% neq 0 (
    echo ERROR: mycommand failed with code %ERRORLEVEL%
    exit /b %ERRORLEVEL%
)

Fail-Fast Pattern

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

Setting Exit Codes

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

Essential Commands Reference

File Operations

CommandPurpose
DIRList directory contents
COPYCopy files
XCOPYExtended copy with subdirectories (legacy)
ROBOCOPYRobust copy with retry, mirror, logging
MOVEMove or rename files
DELDelete files
RENRename files
MD / MKDIRCreate directories
RD / RMDIRRemove directories
MKLINKCreate symbolic or hard links
ATTRIBView or set file attributes
TYPEPrint file contents
MOREPaginated file display
TREEDisplay directory structure
REPLACEReplace files in destination with source
COMPACTShow or set NTFS compression
EXPANDExtract from.cab files
MAKECABCreate.cab archives
TARCreate or extract tar archives

Text Search and Processing

CommandPurpose
FINDSearch for literal strings
FINDSTRSearch with limited regular expressions
SORTSort lines alphabetically
CLIPCopy piped input to clipboard
FCCompare two files
COMPBinary file comparison
CERTUTILEncode/decode Base64, compute hashes

System Information

CommandPurpose
SYSTEMINFOFull system configuration
HOSTNAMEDisplay computer name
VERWindows version
WHOAMICurrent user and group info
TASKLISTList running processes
TASKKILLTerminate processes
WMICWMI queries (drives, OS, memory)
SCService control (query, start, stop)
DRIVERQUERYList installed drivers
REGRegistry operations (query, add, delete)
SETXSet persistent environment variables

Network

CommandPurpose
PINGTest network connectivity
IPCONFIGIP configuration
NSLOOKUPDNS lookup
NETSTATNetwork connections and ports
TRACERTTrace route to host
NET USEMap/disconnect network drives
NET USERManage user accounts
NETSHNetwork configuration utility
ARPARP cache management
ROUTERouting table management
CURLHTTP requests (Windows 10+)
SSHSecure shell (Windows 10+)

Scheduling and Automation

CommandPurpose
SCHTASKSCreate and manage scheduled tasks
TIMEOUTWait N seconds (Vista+)
STARTLaunch programs asynchronously
RUNASRun as different user
SHUTDOWNShutdown or restart
FORFILESFind files by date and execute commands

Shell Utilities

CommandPurpose
WHERELocate executables in PATH
DOSKEYCreate command macros
CHOICEPrompt for single-key input
MODEConfigure console size and ports
SUBSTMap folder to drive letter
CHCPGet or set console code page
COLORSet console colors
TITLESet console window title
ASSOC / FTYPEFile type associations

Shell Syntax and Expressions

Parentheses for Grouping

Parentheses turn compound commands into a single unit for redirection or conditional execution:

(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:

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

Wildcards

  • * matches any sequence of characters
  • ? matches a single character (or zero at end of period-free segment)
dir *.txt           & REM All .txt files
ren *.jpeg *.jpg    & REM Bulk rename

Redirection Summary

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

Writing Production-Quality Batch Files

Standard Script Structure

@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 codesexit /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 stderrecho ERROR: message 1>&2 keeps stdout clean for piping.
  10. Use REM for comments:: can cause issues inside FOR loop bodies.

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.

Debugging and Troubleshooting

TechniqueHow
Trace executionRemove @echo off or use @echo on temporarily
Step throughAdd PAUSE between sections
Check error levelecho Exit code: %ERRORLEVEL% after each command
Inspect variablesset _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 SETset 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 moduloset /a r=14 %% 3 in batch files

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 Keyboard Shortcuts

ShortcutAction
TabAuto-complete file/folder names
Up / DownNavigate command history
F7Show command history popup
F3Repeat last command
EscClear current line
Ctrl+CCancel running command
Alt+F7Clear command history

Reference Files

The references/ folder contains detailed documentation:

FileContents
tools-and-resources.mdWindows tools, utilities, package managers, terminals
batch-files-and-functions.mdExample scripts, techniques, best practices links
windows-commands.mdComprehensive A-Z Windows command reference
cygwin.mdCygwin user guide and FAQ
msys2.mdMSYS2 installation, packages, and environments
windows-subsystem-on-linux.mdWSL setup, commands, and documentation

Asset Templates

The assets/ folder contains starter batch file template data, but as text files:

TemplatePurpose
executable.txtStandalone CLI tool with argument parsing
library.txtReusable function library with CALL-able labels
task.txtScheduled task / automation script

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

36.17%
按下载量换算31

Claude

30.16%
按下载量换算26

Cursor

19.99%
按下载量换算17

Gemini CLI

11.58%
按下载量换算10

安全审计

Gen Agent Trust Hub

可疑

Socket

通过

Snyk

通过

权限和风险

敏感数据

该 Skill 可能接触密钥、Token、环境变量或敏感配置,应进入高风险复核队列,默认不自动发布。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。来源安全扫描存在 warning/failed 结果,不能写成本站确认安全。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills