当前目录不存在:批处理文件

时间:2016-12-24 04:50:11

标签: batch-file

最近我一直在尝试使用批处理文件为我做一些重复的工作,并检查当前目录中是否存在文件是至关重要的。我以前经常使用批处理文件,但我现在正在使用新计算机,而我从dropbox获取的旧批处理文件不起作用,我不确定为什么。考虑批处理脚本:

@echo off
echo Build Verification...
if not exist "%cd%\build.bat" GOTO buildFail
echo Success!
pause
exit

:buildFail
echo Building of mod failed!
pause 
exit

build.bat在当前目录中存在,但这是cmd给我的:

Build Verification...
The syntax of the command is incorrect.
Building of mod failed!
Press any key to continue...

为什么会发生这种情况感到困惑,我尝试了一些变化:

(如果动态目录有问题)

@echo off
echo Build Verification...
if not exist "%~dp0\build.bat" GOTO buildFail
echo Success!
pause
exit

:buildFail
echo Building of mod failed!
pause 
exit

但它产生相同的结果

直接复制目录批发而不使用%dp~0或%cd%也会产生相同的结果。

通过将目录设置为变量也不起作用:

set randdir = "%cd%\build.bat"
if not exist "%randdir%" GOTO buildFail

但这是最奇怪的部分: 调用catch文件

@echo off
echo Build Verification...
call "%cd%\build.bat"

这会导致build.bat

的激活

请帮忙!

3 个答案:

答案 0 :(得分:1)

虽然我无法在您的问题中重现The syntax of the command is incorrect.,但您的计算机可能默认情况下禁用了命令扩展名(不是通常的情况,默认情况下会启用扩展名),这意味着{{ 1}}变量或%cd%值未解析。

尝试在批处理文件的开头包含%~dp0

答案 1 :(得分:1)

我无法在代码中找到语法错​​误的原因,除非您用包含空格或其他标记分隔符的引用字符串覆盖变量CD,,{{1} },;)或其他特殊字符,或包含不平衡引号=的字符串。

例如:

"

结果:

set CD="
if not exist "%CD%\build.bat" echo File not found.

但是,这仍然无法解释执行The syntax of the command is incorrect. 命令的原因。

答案 2 :(得分:1)

这是一个小修改:

@Echo Off
SetLocal EnableExtensions
If /I Not "%__CD__%"=="%~dp0" PushD "%~dp0" 2>Nul||Exit/B 2
Echo=Build Verification...
If Not Exist "build.bat" GoTo buildFail
Echo=Success!
Timeout -1
Exit/B 0

:buildFail
Echo=Building of mod failed!
Timeout -1
Exit/B 1

请告诉我们它是怎么回事。

相关问题