使用 cmd 命令行(不是批处理脚本)检查文件/文件夹是否存在

Nic*_*oul 15 windows command-line

我在 Windows 控制台上试图找出文件/文件夹是否存在。

EXIST 可以批量使用,但在命令行上不可用:

C:\Users\WIN7PR~1>EXIST C:\Users
'EXIST' is not recognized as an internal or external command, operable program or batch file.
Run Code Online (Sandbox Code Playgroud)

kbu*_*ien 16

当资源是文件时,解决方案非常简单,正如其他人所指出的:

C:\> IF EXIST C:\CONFIG.SYS ECHO C:\CONFIG.SYS exists.
Run Code Online (Sandbox Code Playgroud)

不幸的是,以上不适用于目录。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.
Run Code Online (Sandbox Code Playgroud)

事实证明,为了支持像追加>NUL命令语句这样的结构,在每个目录中都有一种名为“NUL”的虚拟文件。检查它的存在等同于检查目录的存在。

此行为记录在 Microsoft 知识库文章 ( https://support.microsoft.com/en-us/kb/65994 ) 中,我已确认其在 FreeDOS 1.1 和 Windows 7 命令外壳中的行为。

额外:知识库文章指出此技术还可用于查看驱动器是否存在。但是,在检查驱动器是否存在的情况下,存在以下警告:

  • Abort, Retry, Fail?,如果驱动器未格式化的错误发生。

  • 使用此技术检查驱动器是否存在取决于设备驱动程序的实现,并且可能并不总是有效。


bum*_*mmi 12

你可以使用一个简单的

DIR C:\User
Run Code Online (Sandbox Code Playgroud)


小智 6

您可以使用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.
Run Code Online (Sandbox Code Playgroud)