How do you use batch IF EXIST to test directories?
此处的批处理可正确插入文件,但为IF EXIST提供奇数输出。我已经通过前后的回声验证了该问题,但是如果复制已结束,则IF EXIST会ping为真。我得到的错误是控制台文本"系统找不到指定的驱动器。"
代码在下面。
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 | ECHO OFF ECHO This batch file will place the background and user icons for Windows 7 install. SET directoryName=C:\\Users\\yourname\\Desktop\\BatchTestingFolder\\ImageInsertReal\\testfolder ECHO %directoryName% PAUSE IF EXIST guest.bmp ( ::If image exists ECHO 1 ::1-- IF EXIST %directoryName% ( ::If directory exists ::insert all below images ::2-- ECHO 2 COPY /-Y guest.bmp %directoryName% ) ELSE ( ::Else echo directory doesnt exist ::2-- ECHO The folder %directoryName% does not exist. goto ENDER ) ) ELSE ( ::Else echo image doesn't exist ::1-- ECHO Images do not exist in current batch file directory. goto ENDER ) ::Exit insertion :ENDER PAUSE |
我强烈建议您使用可读的编码语法。
- 适当的缩进有助于括号代码块的可读性。
- 在括号代码块内使用双冒号作为注释可能会导致不希望的代码输出。
- 您可以使用反斜杠来确保您正在测试目录的存在。
- 使用文件名和文件路径两边的引号来保护空格和特殊字符。
这可能会解决您的问题。
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 | @ECHO OFF ECHO This batch file will place the background and user icons for Windows 7 install. SET"directoryName=C:\\Users\\yourname\\Desktop\\BatchTestingFolder\\ImageInsertReal\\testfolder" ECHO %directoryName% PAUSE IF EXIST guest.bmp ( REM If image exists ECHO 1 REM 1-- IF EXIST"%directoryName%" ( REM If directory exists REM insert all below images REM 2-- ECHO 2 COPY /-Y guest.bmp"%directoryName%" ) ELSE ( REM Else echo directory doesnt exist REM 2-- ECHO The folder %directoryName% does not exist. goto ENDER ) ) ELSE ( REM Else echo image doesn't exist REM 1-- ECHO Images do not exist in current batch file directory. goto ENDER ) ::Exit insertion :ENDER PAUSE |