Batch file 如何在批处理文件中使用条件语句突破for循环?

Batch file 如何在批处理文件中使用条件语句突破for循环?,batch-file,if-statement,for-loop,dos,break,Batch File,If Statement,For Loop,Dos,Break,我正在对大量文件进行处理,我想将我所做的限制在找到的前9个文件。我在一个批处理文件中尝试过这个,但它不起作用。它处理所有文件,并且不会在第9个文件停止。我做错了什么 setlocal set fileCount=0 for %%I in (*.doc) do ( rem do stuff here ... set /a fileCount+=1 if "%fileCount%"=="9" exit ) 问题是%fileCount%在解析时而不是在执行时被扩展,因此它没有考虑执行过

我正在对大量文件进行处理,我想将我所做的限制在找到的前9个文件。我在一个批处理文件中尝试过这个,但它不起作用。它处理所有文件,并且不会在第9个文件停止。我做错了什么

setlocal
set fileCount=0

for %%I in (*.doc) do (
  rem do stuff here ...
  set /a fileCount+=1
  if "%fileCount%"=="9" exit
)

问题是
%fileCount%
在解析时而不是在执行时被扩展,因此它没有考虑执行过程中对
fileCount
的更改。因此,您的
for
-循环相当于:

for %%I in (*.doc) do (
  rem do stuff here ...
  set /a fileCount+=1
  if "0"=="9" exit
)
要更正它,您需要启用并使用延迟扩展。您可以通过使用
setlocalenabledelayedexpansion
而不仅仅是
setlocal
来实现这一点!文件计数而不是
%fileCount%
。因此:

setlocal EnableDelayedExpansion
set fileCount=0

for %%I in (*.doc) do (
  rem do stuff here ...
  set /a fileCount+=1
  if "!fileCount!"=="9" exit
)

有关更多信息,请参阅。

谢谢!我没有发现我遗漏了启用延迟扩展!我一直在和那个女人来往!以及fileCount变量上的%和其他变量。再次感谢!