windows 批量检查盘符是否存在,否则转到另一段代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24060404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if drive letter exists in batch, or else goto another piece of code
提问by Twml
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. What am I doing wrong, so that it won't go to :no?
但它不起作用,它要么转到 :yes 如果 C: 存在,要么显示空白屏幕如果不存在。我做错了什么,所以它不会去:不?
回答by MC ND
The main problem in your code is the if ... else
syntax. 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 ... 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
)
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
)
回答by JohnLBevan
@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
回答by Frank Nocke
Verified to work under Win7.Try with an (existing and non-existing) drive letter of your choice:
经验证可在Win7下工作。尝试使用您选择的(现有和不存在的)驱动器号:
@IF EXIST O:\ (GOTO cont1)
@ECHO not existing
@GOTO end
:cont1
@ECHO existing!
:end