首页 > 解决方案 > 你如何使用批处理 IF EXIST 来测试目录?

问题描述

此处的批处理正确插入文件,但为 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

标签: batch-fileif-statementscriptingdirectory

解决方案


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

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

这可能会解决您的问题。

@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

推荐阅读