batch-file - 你如何使用批处理 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
解决方案
我强烈建议您使用可读的编码语法。
- 适当的缩进有助于括号代码块的可读性。
- 在括号代码块内使用双冒号作为注释可能会导致不需要的代码输出。
- 您可以使用反斜杠来确保您正在测试目录是否存在。
- 在文件名和文件路径周围使用引号来保护空格和特殊字符。
这可能会解决您的问题。
@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
推荐阅读
- tensorflow - 我们可以通过仅省略 pbtxt 标签映射文件中的标签来忽略 Tensorflow 对象检测 API 中不必要的类吗?
- python - Discord Bot Python 如何连接表情符号
- swift - iOS 14 上的 Arkit/SceneKit 引发新警告(金属)
- python - 将第二个 group by 添加到 valuecounts
- python - Python假设包:我可以确保使用某些值吗?
- shell - 基于时间戳和字符串模式的 grep
- python - 如何截断 Mdeditor 的内容(内容为 markdownx) - Django
- mips - MIPS 错误的 MARS 仿真器:地址超出范围 0x20000000
- flutter - 向任何方向滑动以重新加载当前屏幕
- javascript - 密码不显示