The variables are not constant so remember to activate the expansion delayed variable, here the expansion of the variable file
must be delayed.
Delayed Expansion will cause variables to be expanded at execution time rather than at parse time, this option is turned on with the SETLOCAL
command. When delayed expansion is in effect variables can be referenced using !variable_name!
(in addition to the normal %variable_name%
)
Delayed variable expansion is often useful when working with FOR
Loops, normally an entire FOR
loop is evaluated as a single command even if it spans multiple lines of a batch script.
This is the default behaviour of a FOR
loop:
Example :
@echo off
setlocal
:: count to 5 storing the results in a variable
set _tst=0
FOR /l %%G in (1,1,5) Do (echo [%_tst%] & set /a _tst+=1)
echo Total = %_tst%
C:\> demo_batch.cmd
[0]
[0]
[0]
[0]
[0]
Total = 5
Notice that when the FOR
loop finishes we get the correct total, so the variable correctly increments, but during each iteration of the loop
the variable is stuck at it's initial value of 0
The same script with EnableDelayedExpansion
, gives the same final result but also displays the intermediate values:
@echo off
setlocal EnableDelayedExpansion
:: count to 5 storing the results in a variable
set _tst=0
FOR /l %%G in (1,1,5) Do (echo [!_tst!] & set /a _tst+=1)
echo Total = %_tst%
C:\> demo_batch.cmd
[0]
[1]
[2]
[3]
[4]
Total = 5
Notice that within the for loop we use !variable!
instead of %variable%
.
And your batch script can be written like that :
@echo off
Set "Ext=*.gpg"
set /a Count=0
Setlocal EnableDelayedExpansion
for %%F in ("q:\%Ext%") do (
SET /a Count+=1
set "file=%%~nxF"
echo Done copying file [!Count!] : !file!
)
SET /a "COUNT_TOT=%Count%"
ECHO.
ECHO Total of [%EXT%] files(s) : %Count% file(s)
pause