批量计数器不增加

时间:2017-07-27 21:55:42

标签: windows batch-file cmd

代码是不言自明的。我已经尝试了注释行中的命令,结果相同。最后几行是增量分配和证据启用测试扩展工作的测试。故障必须位于for循环中。

@echo off
setlocal EnableDelayedExpansion
set count_k=5

for /l %%a in (1,1,5) do (
rem set a/ count_k+=1
rem set a/ "count_k+=1"
set a/ count_k=count_k+1
echo This is count_k per   %count_k%
echo This is count_k exc  !count_k!
)

echo After loop this is count_k %count_k%

set _var=first
set _var=second & echo %_var% !_var!

set count = 0
(
set /a count+=1
echo %count% fails
echo !count! works
)

这是上述批处理文件的输出:

This is count_k per   5
This is count_k exc  5
This is count_k per   5
This is count_k exc  5
This is count_k per   5
This is count_k exc  5
This is count_k per   5
This is count_k exc  5
This is count_k per   5
This is count_k exc  5
After loop this is count_k 5
first second
 fails
1 works

2 个答案:

答案 0 :(得分:1)

我从未见过" a /" " set"的参数命令之前。您确定它不是" / a",这可能会影响您的结果和代码?

我讨厌分发鱼而不是教鱼,但这与你想做的相似吗?

@ECHO OFF
SET COUNT=0
ECHO Before the loop count is: %COUNT%

FOR /L %%A IN (1,1,5) DO (
  @ECHO Loop %%A
  SET /A COUNT=%COUNT%+%%A
)

ECHO Outside the loop count is: %COUNT%

输出如下:

Before the loop count is: 0
Loop 1
Loop 2
Loop 3
Loop 4
Loop 5
Outside the loop count is: 5

通过重新关闭@ECHO OFF,它看起来像这样:

C:\Users\loginID>REM @ECHO OFF

C:\Users\loginID>SET COUNT=0

C:\Users\loginID>ECHO Before the loop count is: 0
Before the loop count is: 0

C:\Users\loginID>FOR /L %A IN (1 1 5) DO (

 SET /A COUNT=0+%A
)

C:\Users\loginID>(

 SET /A COUNT=0+1
)
Loop 1

C:\Users\loginID>(

 SET /A COUNT=0+2
)
Loop 2

C:\Users\loginID>(

 SET /A COUNT=0+3
)
Loop 3

C:\Users\loginID>(

 SET /A COUNT=0+4
)
Loop 4

C:\Users\loginID>(

 SET /A COUNT=0+5
)
Loop 5

C:\Users\loginID>ECHO Outside the loop count is: 5
Outside the loop count is: 5

请注意,在循环内部,%COUNT%的引用始终为0(从进入循环之前),无论我们在循环内重置多少次。如果我在循环中进行更改

SET / A COUNT + = %% A

我的最终结果回显%COUNT%将导致15.除此之外,我不确定您要实现的目标。

答案 1 :(得分:0)

这适用于Windows 7控制台窗口:

@echo off
setlocal EnableDelayedExpansion
set count_k=5
for /l %%a in (1 1 5) do (
set /a count_k=!count_k!+1
echo !count_k! 
)

请注意,echo%count_k%将输出5,因为%...%类似于在实际运行批处理文件之前执行字符串替换的C预处理器。