如何使用批处理IF EXIST测试目录?

时间:2018-12-06 20:44:34

标签: batch-file if-statement scripting directory

此处的批处理正确插入了文件,但为IF EXIST提供了奇数输出。我已经通过前后的回声验证了该问题,但是如果复制已结束,则IF EXIST将ping为真。我收到的错误是“系统找不到指定的驱动器”的控制台文本。

代码在下面。

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 个答案:

答案 0 :(得分:2)

我强烈建议您使用可读的编码语法。

  • 正确的缩进有助于括号代码块的可读性。
  • 在括号代码块内使用双冒号作为注释可能会导致不希望的代码输出。
  • 您可以使用反斜杠来确保您正在测试目录的存在。
  • 在文件名和文件路径周围使用引号来保护空格和特殊字符。

这可能会解决您的问题。

@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