简体   繁体   English

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

[英]Check if drive letter exists in batch, or else goto another piece of code

I'm trying to make a code that detects if a drive letter exists.我正在尝试制作一个检测驱动器号是否存在的代码。

For example, to check if C: drive exists my code is:例如,要检查 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

But it doesn't work, it either goes to :yes if C: exists or shoes a blank screen if doesn't.但它不起作用,它要么转到 :yes 如果 C: 存在,要么显示空白屏幕如果不存在。 What am I doing wrong, so that it won't go to :no?我做错了什么,所以它不会去:不?

The main problem in your code is the if ... else syntax.您代码中的主要问题是if ... else语法。 The full command needs to be read/parsed as a single block of code.完整的命令需要作为单个代码块读取/解析。 It does not mean that it should be written in a single line, but if it is not, the lines must include information to the parser so it knows the command continues on the next line这并不意味着它应该写在一行中,但如果不是,则这些行必须包含解析器的信息,以便它知道命令在下一行继续

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
)

Any of the previous codes will work as intended.以前的任何代码都可以按预期工作。

Anyway, the checking for the root folder of the drive will generate a popup for some kind of drives (in my case it was the multi card reader).无论如何,检查驱动器的根文件夹将为某种驱动器生成一个弹出窗口(在我的情况下它是多卡读卡器)。 To avoid it, use instead the vol command and check for errorlevel为避免这种情况,请改用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

Try by including ' echo no '.尝试包括' echo no '。 Use this under ':no'在 ':no' 下使用

Verified to work under Win7.经验证可在Win7下工作。 Try with an (existing and non-existing) drive letter of your choice:尝试使用您选择的(现有和不存在的)驱动器号:

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

:cont1
@ECHO existing!

:end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM