我正在尝试编写一个代码来检测驱动器号是否存在。
例如,要检查 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
但是它不起作用,如果 C: 存在,它要么转到 :yes,要么如果不存在,则显示空白屏幕。我做错了什么,所以它不会去:不?
代码中的主要问题是
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
已验证可在 Win7 下运行。 尝试使用您选择的(现有和不存在)驱动器盘符:
@IF EXIST O:\ (GOTO cont1)
@ECHO not existing
@GOTO end
:cont1
@ECHO existing!
:end
尝试添加“echo no”。在 ':no' 下使用这个
哼哼!
C:\>net use
Status Local Remote Network
----------------------------------------------------------------------------
OK A: \\ENTDC01\Accounting_LawCorp Microsoft Windows Network
OK B: \\ENTDC01\Accounting_LLP Microsoft Windows Network
OK G: \\ENTDC01\GenShares Microsoft Windows Network
OK I: \\ENTDC01\ID Microsoft Windows Network
OK K: \\entdc01\KO_Holdings Microsoft Windows Network
OK L: \\ENTDC01\Library Microsoft Windows Network
OK P: \\ENTDC01\PDrives\rokimaw Microsoft Windows Network
OK Q: \\ENTDC01\soluno Microsoft Windows Network
OK S: \\entdc01\Synergy Scans Microsoft Windows Network
The command completed successfully.
c:\>if exist g:\ ( echo yes) else (echo no)
no
c:\>if exist p:\ ( echo yes) else (echo no)
yes