[英]Check if drive letter exists in batch, or else goto another piece of code
我正在尝试制作一个检测驱动器号是否存在的代码。
例如,要检查 C: 驱动器是否存在,我的代码是:
@echo off
title If Exist Test
:main
CLS
echo.
echo press any key to see if drive C:\ exists
echo.
pause>nul
IF EXIST C:\ GOTO yes
ELSE GOTO no
:yes
cls
echo yes
pause>nul
exit
:no
cls
pause>nul
exit
但它不起作用,它要么转到 :yes 如果 C: 存在,要么显示空白屏幕如果不存在。 我做错了什么,所以它不会去:不?
您代码中的主要问题是if ... else
语法。 完整的命令需要作为单个代码块读取/解析。 这并不意味着它应该写在一行中,但如果不是,则这些行必须包含解析器的信息,以便它知道命令在下一行继续
if exist c:\ ( echo exists ) else ( echo does not exist)
----
if exist c:\ (
echo exists
) else echo does not exist
----
if exist c:\ ( echo exists
) else echo does not exist
----
if exist c:\ (
echo exists
) else (
echo does not exist
)
以前的任何代码都可以按预期工作。
无论如何,检查驱动器的根文件夹将为某种驱动器生成一个弹出窗口(在我的情况下它是多卡读卡器)。 为避免这种情况,请改用vol
命令并检查错误级别
vol w: >nul 2>nul
if errorlevel 1 (
echo IT DOES NOT EXIST
) else (
echo IT EXISTS
)
@echo off title If Exist Test :main CLS echo. echo press any key to see if drive C:\ exists echo. pause>nul ::NB: you need the brackets around the statement so that the file ::knows that the GOTO is the only statement to run if the statement ::evaluates to true, and the ELSE is separate to that. IF EXIST C:\ (GOTO yes) ELSE (GOTO no) ::I added this to help you see where the code just runs on to the ::next line instead of obeying your goto statements echo no man's land :yes ::cls echo yes pause>nul exit :no ::cls echo no pause>nul exit
尝试包括' echo no '。 在 ':no' 下使用
经验证可在Win7下工作。 尝试使用您选择的(现有和不存在的)驱动器号:
@IF EXIST O:\ (GOTO cont1)
@ECHO not existing
@GOTO end
:cont1
@ECHO existing!
:end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.