[英]Check if drive letter exists in batch, or else goto another piece of code
我正在嘗試制作一個檢測驅動器號是否存在的代碼。
例如,要檢查 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
但它不起作用,它要么轉到 :yes 如果 C: 存在,要么顯示空白屏幕如果不存在。 我做錯了什么,所以它不會去:不?
您代碼中的主要問題是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
嘗試包括' echo no '。 在 ':no' 下使用
經驗證可在Win7下工作。 嘗試使用您選擇的(現有和不存在的)驅動器號:
@IF EXIST O:\ (GOTO cont1)
@ECHO not existing
@GOTO end
:cont1
@ECHO existing!
:end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.