首页 > 解决方案 > 如何检查 IF Exist 中是否存在其中一个或文件?

问题描述

如何检查 If Exist 语句中是否存在其中一个或文件?

If exist "C:/Windows/" OR "C:/Windows2" (
Do something
) else (
Something else
)

我该怎么做?我只想要么存在,要么做点什么。

标签: if-statementbatch-fileexists

解决方案


简单示例1:

@echo off
if not exist "%SystemRoot%\" if not exist "C:\Windows2" goto MissingFolderFile
echo Found either the directory %SystemRoot% or the file/folder C:\Windows2.
rem Insert here more commands to run on either the folder C:\Windows
rem or the file/folder (=any file system entry) C:\Windows2 existing.
goto EndDemo

:MissingFolderFile
echo There is neither the directory %SystemRoot% nor the file/folder C:\Windows2.
rem Insert here more commands to run on neither folder C:\Windows
rem nor file/folder C:\Windows2 existing.

:EndDemo
pause

Windows 命令处理器设计用于处理一个接一个的命令行,这就是批处理这个词的含义。命令GOTO是在批处理文件中使用的首选命令,它不是在下一个命令行上继续批处理,而是在另一个取决于IF条件的命令行上,即将处理从命令行的一个堆栈(批处理的另一个词)更改为另一组的命令行。

简单示例2:

@echo off
if exist "%SystemRoot%\" goto FolderExists
if exist "C:\Windows2" goto FS_EntryExists
echo There is neither the directory %SystemRoot%\ nor C:\Windows2.
rem Insert here more commands to run on neither folder C:\Windows
rem nor file/folder/reparse point C:\Windows2 existing.
goto EndDemo

:FS_EntryExists
echo The file system entry (file or folder) C:\Windows2 exists.
rem Insert here more commands to run on C:\Windows2 existing.
goto EndDemo

:FolderExists
echo The folder %SystemRoot% exists.
rem Insert here more commands to run on folder C:\Windows existing.

:EndDemo
pause

要了解所使用的命令及其工作原理,请打开命令提示符窗口,在其中执行以下命令,并仔细阅读每个命令显示的所有帮助页面。

  • echo /?
  • goto /?
  • if /?
  • rem /?

笔记:

Windows 上的目录分隔符\/Linux 或 Mac 不同。Windows 文件管理通常会在将不带或带通配符模式的文件/文件夹参数字符串传递给文件系统之前自动替换所有内容/\如 Microsoft 在有关命名文件、路径和命名空间的文档中所解释的那样。但是在文件/文件夹参数字符串中使用/而不是\可能会导致意外行为。

/由于在命令提示符窗口中直接运行以下命令行而导致的意外行为示例:

for %I in ("%SystemDrive%/Windows/*.exe") do @if exist "%I" (echo Existing file: "%I") else echo File not found: "%I"

此命令行输出由FOR在 Windows 目录中找到的可执行文件名列表,这些文件名对于命令IF不存在,只是因为使用/导致将找到的文件名分配给循环变量而没有路径。因此,此命令行仅在系统驱动器上的当前目录偶然是 Windows 目录时才有效。

使用\as 目录分隔符的相同命令行:

for %I in ("%SystemDrive%\Windows\*.exe") do @if exist "%I" (echo Existing file: "%I") else echo File not found: "%I"

此命令行将 Windows 目录中可执行文件的每个文件名输出为具有完整路径的现有文件。

另一个例子:

当前驱动器的根目录下有一个目录Downloads,该驱动器上的当前目录是Temp,例如D:\Downloads是想要的当前目录,D:\Temp是当前目录。

使用的命令是:

cd /Downloads

结果是错误消息:

该系统找不到指定的路径。

正确使用目录分隔符的命令:

cd \Downloads

此命令适用于D:\Temp当前目录和D:\Downloads现有目录。

CD将不正确的目录路径开头/Downloads的字符串解释为也更改驱动器的选项,并在当前目录而不是当前驱动器的根目录中搜索该原因。通过使用正确的目录参数字符串,可以避免CD的这种错误解释。/D/DownloadsDownloads\Downloads

摘要:\是目录分隔符,/用于命令选项。


推荐阅读