批处理文件切换操作

批处理文件切换操作

我尝试使用一个简单的 .bat 文件来运行两个操作。第一次运行该文件时,它会继续执行一个命令,第二次运行它时,它会执行另一个命令... 重复上述步骤。

在不知道内部工作原理的情况下,我猜想它需要创建一个文件来告知它处于什么状态。我的知识就到此为止了。有什么简单的方法可以实现这一点?

答案1

有。使用这篇关于 stack overflow 的帖子作为一个例子,我得到:

(创建一个名为first_run的文件)

复制 con first_run
四十二
^z

(创建一个批处理文件,检查 first_run 是否存在)

复制 con mycommand.bat
欢迎来到 my_command.bat
暂停  

如果存在 D:\first_run
启动/等待第一个命令

echo 您的第一个命令已执行。立即终止。
转到:EOF

echo first_run 标记未找到。
echo 启动第二个命令。
启动第二个命令
^Z

goto 结尾很丑陋。我确信一定有更干净的方法。但我已经很久没有使用过批处理文件了。

改为goto :EOF。谢谢 Karan,很好的建议。

答案2

如果我没看错的话,您希望批处理文件运行 executableA.exe 然后终止。下次运行时,您希望它启动 executableB.exe 并终止。然后下次运行时,您希望它再次运行 executableA.exe。

一个简单的方法是创建一个这样的标记文件:

@echo off
REM change the current working directory to where the batch script is located
cd /d %~dp0

if exist %~dp0Anext.txt (
  call :A
  goto :EOF
)
if exist %~dp0Bnext.txt (
  call :B
  goto :EOF
)
if not exist %~dp0*next.txt (
  call :firstrun
  goto :EOF
)
goto :EOF

REM subroutines only below this point:
:A
REM you would launch executableA.exe here
echo AAA
echo B > Bnext.txt
del Anext.txt
goto :EOF

:B
REM you would launch executableB.exe here
echo BBB
echo A > Anext.txt
del Bnext.txt
goto :EOF

:firstrun
REM you would launch executableA.exe here
echo AAA
echo B > Bnext.txt
goto :EOF

如果您想扩展它,您可以按照相同的逻辑使其在三个或更多可执行文件/脚本之间轮换。

答案3

前面的答案思路正确,但可以简化。

IF EXIST "checkfile.log" GOTO Toggle_on

:Toggle_Off
ECHO ToggleOn >"checkfile.log"
REM 1st Execute Actions

REM ::: Script Break ~ EXIT / GOTO :EOF

:Toggle_On
Del /Q "checkfile.log"
REM 2nd Execute Actions

相关内容