如何验证批处理文件中是否存在一个文件?

我必须创建一个.BAT文件来完成以下工作:

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

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

541518 次浏览

你可以使用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
)

输入IF /?为了获得有关if的帮助,它清楚地解释了如何使用if EXIST。

要删除除某些文件夹外的完整树,请参阅问题的答案:Windows批处理脚本删除文件夹中除了一个以外的所有内容

最后,复制只意味着调用COPY和调用另一个bat文件,可以这样做:

MYOTHERBATFILE.BAT sync.bat myprogram.ini

下面是一个很好的例子,说明在文件存在或不存在的情况下如何执行命令:

if exist C:\myprogram\sync\data.handler echo Now Exiting && Exit
if not exist C:\myprogram\html\data.sql Exit

我们会把这三个文件放到一个临时的地方。删除文件夹后,它将恢复这三个文件。

xcopy "test" "C:\temp"
xcopy "test2" "C:\temp"
del C:\myprogram\sync\
xcopy "C:\temp" "test"
xcopy "C:\temp" "test2"
del "c:\temp"

使用选择复制文件命令:

xcopy "C:\myprogram\html\data.sql"  /c /d /h /e /i /y  "C:\myprogram\sync\"

我将解释/c /d /h /e /i /y的含义:

  /C           Continues copying even if errors occur.
/D:m-d-y     Copies files changed on or after the specified date.
If no date is given, copies only those files whose
source time is newer than the destination time.
/H           Copies hidden and system files also.
/E           Copies directories and subdirectories, including empty ones.
Same as /S /E. May be used to modify /T.
/T           Creates directory structure, but does not copy files. Does not
include empty directories or subdirectories. /T /E includes
/I           If destination does not exist and copying more than one file,
assumes that destination must be a directory.
/Y           Suppresses prompting to confirm you want to overwrite an
existing destination file.


`To see all the commands type`xcopy /? in cmd

用sync.bat myprogram.ini选项调用其他批处理文件。

我不知道你说的是什么意思,但如果你想打开这两个文件你只需要把文件的路径设置为

Path/sync.bat
Path/myprogram.ini
如果是在Bash环境中,对我来说很容易,但我没有 知道如何测试文件或文件夹是否存在,以及它是否是一个文件或 文件夹。< / p >

您正在使用批处理文件。你之前提到过,你必须创建一个.bat文件来使用它:

我必须创建一个。bat文件,这样做: