如果无法识别命令,则窗口脚本将自行退出

时间:2015-04-13 17:11:42

标签: batch-file command-line window

如果命令未被识别为内部或外部命令,我想编写一个窗口脚本来退出脚本。

我可以知道如何实现这一目标吗?真的需要一些帮助,因为窗口cmd文档和示例是有限的。

我尝试过:

somecommand
if errorlevel 0 exit /b

但它似乎不起作用,因为errorlevel的值保持为0,即使我在“命令未被识别为内部或外部命令”时出现错误

提前致谢

最好的问候

3 个答案:

答案 0 :(得分:1)

使用

编写一个简短的批处理文件(一个简单的文本文件)
@echo off
%* 2>nul || echo No such command: %*

仅当前一个命令失败时,||运算符才会启动下一个命令(此处为echo)。

答案 1 :(得分:0)

对于大于或等于if errorlevel n的任何错误级别值,n将被评估为 true 。所以if errorlevel 0对于任何非负误差水平都是正确的。

当无法识别命令时,errorlevel值设置为9009,因此您可以尝试使用

somecommand
if %errorlevel% equ 9009 echo does not exist

somecommand
if not errorlevel 9010 if errorlevel 9009 echo does not exist

当然,任何现有程序都可以设置errorlevel 9009,因此这不是防弹方法。

答案 2 :(得分:0)

@echo off  
ver > nul  
echo ERRORLEVEL : %ERRORLEVEL%    
some command  
IF %ERRORLEVEL% NEQ 0 ( goto PrintError )  

:PrintError  
echo Command is not recognized as internal or external command!  

exit /B 1