批量检查盘符是否存在,否则转到另一段代码

问题描述 投票:0回答:5

我正在尝试编写一个代码来检测驱动器号是否存在。

例如,要检查 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,要么如果不存在,则显示空白屏幕。我做错了什么,所以它不会去:不?

windows batch-file cmd
5个回答
25
投票

代码中的主要问题是

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
)

7
投票
@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

0
投票

已验证可在 Win7 下运行。 尝试使用您选择的(现有和不存在)驱动器盘符:

@IF EXIST O:\ (GOTO cont1)
@ECHO not existing
@GOTO end

:cont1
@ECHO existing!

:end

0
投票

尝试添加“echo no”。在 ':no' 下使用这个


0
投票

哼哼!

 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
© www.soinside.com 2019 - 2024. All rights reserved.