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:
@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?
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 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 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 ' '. '。 Use this under ':no'
Verified to work under 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.