如何验证批处理文件中是否存在文件? [英] How to verify if a file exists in a batch file?

查看:98
本文介绍了如何验证批处理文件中是否存在文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have to create a .BAT file that does this:

  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调用其他批处理文件.
  1. If C:\myprogram\sync\data.handler exists, exit;
  2. If C:\myprogram\html\data.sql does not exist, exit;
  3. In C:\myprogram\sync\ delete all files and folders except (test, test3 and test2)
  4. Copy C:\myprogram\html\data.sql to C:\myprogram\sync\
  5. Call other batch file with option sync.bat myprogram.ini.

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

If it was in the Bash environment it was easy for me, but I do not know how to test if a file or folder exists and if it is a file or folder.

推荐答案

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

You can use IF EXIST to check for a file:

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

如果您不需要"else",则可以执行以下操作:

If you do not need an "else", you can do something like this:

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=

以下是搜索文件或文件夹的有效示例:

Here's a working example of searching for a file or a folder:

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
)

这篇关于如何验证批处理文件中是否存在文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆