系统命令

if 命令

按条件执行命令;命令扩展还支持 /i、defined、cmdextversion 和比较运算符。

适用版本/范围: Microsoft Learn Windows 客户端与 Windows Server 命令参考;部分条目可能属于旧版命令、服务器角色、可选功能或交互式工具子命令。English

官方文档语法

if [not] ERRORLEVEL <number> <command> [else <expression>]
if [not] <string1>==<string2> <command> [else <expression>]
if [not] exist <filename> <command> [else <expression>]
If command extensions are enabled, use the following syntax:
if [/i] <string1> <compareop> <string2> <command> [else <expression>]
if cmdextversion <number> <command> [else <expression>]
if defined <variable> <command> [else <expression>]

链接的 Microsoft Learn 文章是上游依据;命令是否可用取决于 Windows 版本、服务器角色、可选功能或交互式工具上下文。

用法示例

按条件执行命令;命令扩展还支持 /i、defined、cmdextversion 和比较运算符。

if exist config.ini type config.ini

参数、选项与子句

参数 / 子句说明
not反转条件结果。
ERRORLEVEL <number>检查上一个程序的退出代码是否大于或等于指定值。
exist <filename>检查文件是否存在。
<string1>==<string2>比较两个字符串。
/i启用命令扩展时进行不区分大小写的字符串比较。
defined <variable> / cmdextversion <number>检查变量是否已定义,或检查命令扩展版本。
<command>Microsoft Learn 列出的参数或子命令;所需格式与运行上下文请查看官方来源。
<expression>Microsoft Learn 列出的参数或子命令;所需格式与运行上下文请查看官方来源。
<compareop>Microsoft Learn 列出的参数或子命令;所需格式与运行上下文请查看官方来源。
安全提示

执行前请核对命令和目标路径。修改文件、服务、账户、磁盘、权限或数据库的操作可能难以撤销;建议先在安全环境测试并保留备份。

参考文档 ↗返回目录