gpt4 book ai didi

batch-file - 批处理文件 - 等待文件循环

转载 作者:行者123 更新时间:2023-12-02 15:15:31 28 4
gpt4 key购买 nike

我正在尝试制作一个非常简单的 bat 文件。

在 for 循环中,我调用另一个应用程序,它会为我创建一个文件。生成该文件后,我想再次执行此操作,直到循环完成。在再次运行循环之前,我需要等待创建文件。

我需要使用STARTCALL,因为在创建文件后我会终止进程。它不包含在下面的代码中,但它是必需的。

@echo off

for /L %%i in (1,1,5) do (
SET filename=fooFile_%%i.txt
START /B CMD /C CALL createFile.bat fooFile_%%i.txt

:waitfile
ECHO waitforfile: %filename%
TIMEOUT /T 10 >nul
IF EXIST %filename% GOTO FoundIt
goto waitfile

:FoundIt
ECHO Found file %filename%
)
ECHO All done!

还有我的createFile.bat。这实际上是另一个应用程序。但是下面的代码足以模拟它:

@echo off

set arg1=%1
TIMEOUT /T 10 >nul
copy NUL %arg1%
ECHO Created file

当前输出:

waitforfile:
waitforfile fooFile_1.txt
1 file(s) copied.
Created file
Found file fooFile_1.txt
All done!

正如您从输出中看到的那样,我无法让循​​环与我的 GOTO 一起工作。我看过这些问题:

Batch file goto not working in for loop

(Windows batch) Goto within if block behaves very strangely

将循环与 goto 结合起来似乎是个坏主意。那么我该如何解决我的问题呢?

最佳答案

1) 要使用可能在循环中更改的变量,请使用 EnableDelayedExpansion!var! 而不是 %var%

2) 将:waitfile 移动到一个sub

@echo off
setlocal EnableDelayedExpansion

for /L %%i in (1,1,5) do (
SET filename=fooFile_%%i.txt
START /B CMD /C CALL createFile.bat fooFile_%%i.txt

call :waitfile "!filename!"

ECHO Found file !filename!
)
ECHO All done!
exit /b 0

:waitfile
ECHO waitforfile: %~1
:waitfile2
TIMEOUT /T 10 >nul
IF not EXIST "%~1" goto waitfile2
exit /b 0

关于batch-file - 批处理文件 - 等待文件循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40883430/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com