
- 批处理脚本教程
- 批处理脚本 - 首页
- 批处理脚本 - 概述
- 批处理脚本 - 环境
- 批处理脚本 - 命令
- 批处理脚本 - 文件
- 批处理脚本 - 语法
- 批处理脚本 - 变量
- 批处理脚本 - 注释
- 批处理脚本 - 字符串
- 批处理脚本 - 数组
- 批处理脚本 - 决策
- 批处理脚本 - 运算符
- 批处理脚本 - 日期和时间
- 批处理脚本 - 输入/输出
- 批处理脚本 - 返回代码
- 批处理脚本 - 函数
- 批处理脚本 - 进程
- 批处理脚本 - 别名
- 批处理脚本 - 设备
- 批处理脚本 - 注册表
- 批处理脚本 - 网络
- 批处理脚本 - 打印
- 批处理脚本 - 调试
- 批处理脚本 - 日志记录
- 批处理脚本资源
- 批处理脚本 - 快速指南
- 批处理脚本 - 有用资源
- 批处理脚本 - 讨论
批处理脚本 - 注释
为创建的脚本添加注释或文档始终是一个好习惯。这对于维护脚本以了解脚本的实际作用是必需的。
例如,考虑以下没有任何形式注释的代码片段。如果任何未开发以下脚本的普通用户尝试理解该脚本,则该用户需要花费大量时间才能理解脚本的实际作用。
ECHO OFF IF NOT "%OS%"=="Windows_NT" GOTO Syntax ECHO.%* | FIND "?" >NUL IF NOT ERRORLEVEL 1 GOTO Syntax IF NOT [%2]==[] GOTO Syntax SETLOCAL SET WSS= IF NOT [%1]==[] FOR /F "tokens = 1 delims = \ " %%A IN ('ECHO.%~1') DO SET WSS = %%A FOR /F "tokens = 1 delims = \ " %%a IN ('NET VIEW ^| FIND /I "\\%WSS%"') DO FOR /F "tokens = 1 delims = " %%A IN ('NBTSTAT -a %%a ^| FIND /I /V "%%a" ^| FIND "<03>"') DO ECHO.%%a %%A ENDLOCAL GOTO:EOF ECHO Display logged on users and their workstations. ECHO Usage: ACTUSR [ filter ] IF "%OS%"=="Windows_NT" ECHO Where: filter is the first part of the computer name^(s^) to be displayed
使用 Rem 语句添加注释
在批处理脚本中创建注释有两种方法;一种是通过 Rem 命令。Rem 语句后面的任何文本都将被视为注释,并且不会被执行。以下是此语句的通用语法。
语法
Rem Remarks
其中“备注”是要添加的注释。
以下示例展示了Rem命令的简单用法。
示例
@echo off Rem This program just displays Hello World set message=Hello World echo %message%
输出
以上命令产生以下输出。您会注意到包含 Rem 语句的行不会被执行。
Hello World
使用 :: 语句添加注释
在批处理脚本中创建注释的另一种方法是通过 :: 命令。:: 语句后面的任何文本都将被视为注释,并且不会被执行。以下是此语句的通用语法。
语法
:: Remarks
其中“备注”是要添加的注释。
以下示例展示了“::”命令的用法。
示例
@echo off :: This program just displays Hello World set message = Hello World echo %message%
输出
以上命令产生以下输出。您会注意到包含 :: 语句的行不会被执行。
Hello World
注意 - 如果您有太多行的 Rem,它可能会降低代码速度,因为最终批处理文件中的每一行代码仍然需要执行。
让我们看看在本主题开头看到的那个大型脚本的示例,看看添加了文档后它是什么样子。
::=============================================================== :: The below example is used to find computer and logged on users :: ::=============================================================== ECHO OFF :: Windows version check IF NOT "%OS%"=="Windows_NT" GOTO Syntax ECHO.%* | FIND "?" >NUL :: Command line parameter check IF NOT ERRORLEVEL 1 GOTO Syntax IF NOT [%2]==[] GOTO Syntax :: Keep variable local SETLOCAL :: Initialize variable SET WSS= :: Parse command line parameter IF NOT [%1]==[] FOR /F "tokens = 1 delims = \ " %%A IN ('ECHO.%~1') DO SET WSS = %%A :: Use NET VIEW and NBTSTAT to find computers and logged on users FOR /F "tokens = 1 delims = \ " %%a IN ('NET VIEW ^| FIND /I "\\%WSS%"') DO FOR /F "tokens = 1 delims = " %%A IN ('NBTSTAT -a %%a ^| FIND /I /V "%%a" ^| FIND "<03>"') DO ECHO.%%a %%A :: Done ENDLOCAL GOTO:EOF :Syntax ECHO Display logged on users and their workstations. ECHO Usage: ACTUSR [ filter ] IF "%OS%"=="Windows_NT" ECHO Where: filter is the first part of the computer name^(s^) to be displayed
您现在可以看到,对于未开发代码的用户来说,代码变得更容易理解,因此更易于维护。
广告