windows - 如何验证批处理文件中的文件是否存在?

标签 windows batch-file cmd

我必须创建一个 .BAT 文件来执行此操作:

  1. 如果C:\myprogram\sync\data.handler存在,则退出;
  2. 如果C:\myprogram\html\data.sql不存在,则退出;
  3. C:\myprogram\sync\ 中删除除(testtest3test2)之外的所有文件和文件夹
  4. C:\myprogram\html\data.sql复制到C:\myprogram\sync\
  5. 使用选项 sync.bat myprogram.ini 调用其他批处理文件。

如果是在 Bash 环境中对我来说很容易,但我不知道如何测试文件或文件夹是否存在以及是否是文件或文件夹。

最佳答案

您可以使用 IF EXIST 来检查文件:

IF EXIST "filename" (
  REM Do one thing
) ELSE (
  REM Do another thing
)

如果你不需要“else”,你可以这样做:

set __myVariable=
IF EXIST "C:\folder with space\myfile.txt" set __myVariable=C:\folder with space\myfile.txt
IF EXIST "C:\some other folder with space\myfile.txt" set __myVariable=C:\some other folder with space\myfile.txt
set __myVariable=

以下是搜索文件或文件夹的工作示例:

REM setup

echo "some text" > filename
mkdir "foldername"

REM finds file    

IF EXIST "filename" (
  ECHO file filename exists
) ELSE (
  ECHO file filename does not exist
)

REM does not find file

IF EXIST "filename2.txt" (
  ECHO file filename2.txt exists
) ELSE (
  ECHO file filename2.txt does not exist
)

REM folders must have a trailing backslash    

REM finds folder

IF EXIST "foldername\" (
  ECHO folder foldername exists
) ELSE (
  ECHO folder foldername does not exist
)

REM does not find folder

IF EXIST "filename\" (
  ECHO folder filename exists
) ELSE (
  ECHO folder filename does not exist
)

关于windows - 如何验证批处理文件中的文件是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25286282/

相关文章:

windows - Windows XP 引导加载程序 (NTLDR) 是否注意内核导入声明?

windows - CTRL+C、CTRL+V、在 Windows cmd 中通过 SHIFT + 箭头选择文本

Matlab,dos()命令: files remain "in use"

c - Windows C 对话框大小调整器

windows - 如何获得在 vbscript 中运行的单行 xcopy 命令?

windows - 运行 cgi 程序时 Apache 服务是否有连接/内存限制?

Windows Batch - 如何修改文件并仅保留以 "<?xml"开头并以 "</testsuites>"结尾的子字符串?

windows - 批处理文件跳过 If 语句

batch-file - 为什么 forfiles 吞下命令的第一个参数?

windows - Windows 下 Puppet/Vagrant 中的颜色编码?