How to verify if a file exists in a batch file?
我必须创建一个执行此操作的
如果它在Bash环境中对我来说很容易,但我不知道如何测试文件或文件夹是否存在以及它是文件还是文件夹。
您可以使用IF EXIST检查文件:
1 2 3 4 5 | IF EXIST"filename" ( REM Do one thing ) ELSE ( REM Do another thing ) |
如果你不需要"其他",你可以这样做:
1 2 3 4 | 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= |
这是搜索文件或文件夹的工作示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | 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文件可以这样做:
1 | MYOTHERBATFILE.BAT sync.bat myprogram.ini |
以下是如果文件存在或不存在时如何执行命令的一个很好的示例:
1 2 | if exist C:\myprogram\sync\data.handler echo Now Exiting && Exit if not exist C:\myprogram\html\data.sql Exit |
我们将把这三个文件放在一个临时的地方。删除文件夹后,它将恢复这三个文件。
1 2 3 4 5 6 | xcopy"test""C:\temp" xcopy"test2""C:\temp" del C:\myprogram\sync\ xcopy"C:\temp""test" xcopy"C:\temp""test2" del"c:\temp" |
使用XCOPY命令:
1 | xcopy"C:\myprogram\html\data.sql" /c /d /h /e /i /y "C:\myprogram\sync" |
我将解释
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | /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 |
Call other batch file with option sync.bat myprogram.ini.
我不确定你的意思,但如果你只想打开这两个文件,你只需要把文件的路径放在一边
1 2 | Path/sync.bat Path/myprogram.ini |
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.
您正在使用批处理文件。您之前提到过必须创建一个.bat文件才能使用它:
I have to create a .BAT file that does this: