批处理文件 - 命令的语法不正确

Batchfile - The syntax of the command is incorrect

我是 Minecraft 服务器的所有者,目前正在研究制作自动设置脚本的方法,以便其他人可以更轻松地 运行 服务器。我已完成所有操作,但在测试时,此代码抛出 "The syntax of the command is incorrect" 错误。这是代码:

@ECHO OFF
SETLOCAL EnableDelayedExpansion
ECHO Welcome to the startup of your new Minecraft server^^!
ECHO Upon completion of the first start, please exit the program and run "start.bat".
ECHO When you are ready, press any key.
PAUSE>NUL
SET /p "hasrun" = < "%~dp0\hasrun.txt"

:Run
IF "!hasrun!" == "0" (
    ECHO "1" >> "%~dp0\hasrun.txt"
    java -Xms1024M -Xmx1024M -jar minecraft_server.jar nogui
) ELSE (
    ECHO This is not your first run^^! Use "start.bat" instead^^!
    PAUSE
)

错误似乎出现在 ECHO "1" >> "%~dp0\hasrun.txt" 行。自从我上次批量写任何东西以来已经有一段时间了,所以这很可能是显而易见的。确切的输出(回声关闭)是:

Welcome to the startup of your new Minecraft server!  
Upon completion of the first start, please exit the program and run "start.bat".

When you are ready, press any key.

按一个键通过 PAUSE 后,它说:

The syntax of the command is incorrect.
This is not your first run! Use "start.bat" instead!
Press any key to continue...

另外,hasrun.txt的内容就是一个零。 (“0”不带引号)

您的问题是变量 !hasrun!。您设置变量的方法会生成一个空变量或无效变量,如果文件为空,则 !hasrun! 不等于任何内容,这将导致 for 循环失败。


@ECHO OFF
SETLOCAL EnableDelayedExpansion
ECHO Welcome to the startup of your new Minecraft server^^!
ECHO Upon completion of the first start, please exit the program and run "start.bat".
ECHO When you are ready, press any key.
PAUSE>NUL
:: Default variable set, or the for loops fails because "" does not equal "0".
if not exist "%~dp0\hasrun.txt" echo 0 >%~dp0\hasrun.txt
:: Set the file to a variable.
SET /p hasrun=<%~dp0\hasrun.txt

:Run
:: Space after "0 " appended because 0> refers to a debugging echo.
IF "!hasrun!"=="0 " (
    ECHO 1>"%~dp0\hasrun.txt"
    java -Xms1024M -Xmx1024M -jar minecraft_server.jar nogui
    pause
) ELSE (
    ECHO This is not your first run^^! Use "start.bat" instead^^!
    PAUSE
)
del %~dp0\hasrun.txt