
我在 Windows 控制台上試圖找出文件/資料夾是否存在。
EXIST
可以批量使用,但在命令列上不可用:
C:\Users\WIN7PR~1>EXIST C:\Users
'EXIST' is not recognized as an internal or external command, operable program or batch file.
答案1
當資源是文件時,解決方案非常簡單,如其他人所示:
C:\> IF EXIST C:\CONFIG.SYS ECHO C:\CONFIG.SYS exists.
不幸的是,上面的方法不適用於目錄。 EXIST 函數對於遺失和存在的資料夾傳回相同的結果。幸運的是,有一個晦澀的解決方法:
C:\> IF NOT EXIST C:\FOLDER\NUL ECHO C:\FOLDER missing.
C:\FOLDER missing.
C:\> MD C:\FOLDER
C:\> IF EXIST C:\FOLDER\NUL ECHO C:\FOLDER exists.
C:\FOLDER exists.
事實證明,為了支援諸如附加>NUL
命令語句之類的結構,每個目錄中都有一個名為「NUL」的虛擬檔案。檢查其是否存在相當於檢查目錄是否存在。
此行為記錄在 Microsoft 知識庫文章 (https://support.microsoft.com/en-us/kb/65994)並且我已經確認了它在 FreeDOS 1.1 和 Windows 7 命令 shell 中的行為。
額外:知識庫文章顯示此技術也可用於查看磁碟機是否存在。然而,在檢查驅動器是否存在時,存在警告:
Abort, Retry, Fail?
如果磁碟機未格式化,則會發生錯誤。使用此技術檢查驅動器是否存在取決於設備驅動程式的實現,並且可能並不總是有效。
答案2
您可以使用一個簡單的
DIR C:\User
答案3
您可以使用type
命令,它將返回文本文件的內容而不打開它,對於目錄它將返回:訪問被拒絕。
如果檔案或目錄不可用,您將收到訊息:系統找不到指定的檔案。
例如:
C:\>type c:\temp
Access is denied.
C:\>type c:\example.txt
Some example content in a text file
C:\>type c:\doesnotexist
The system cannot find the file specified.
答案4
您可以使用此程式碼:
<pre>
:init
SETLOCAL enabledelayedexpansion
GOTO make_dir
:make_dir
ECHO .
ECHO Checking if exists directory %out_path% ...
CD %out_path%
IF !ERRORLEVEL! GTR 0 (
ECHO Directory doesn't exist, creating...
MD %out_path%
GOTO make_dir
) ELSE (
ECHO Directory already exists.
)
:GOTO back_it_up
:back_it_up
::Procedure that makes an backup
GOTO done
:done
ECHO Finished
SETLOCAL
EXIT /B
</pre>