0

I would keep making a script to check the number of files in folders. To do this I stored my folders in an array like this:

set myArray[0]="C:\testFolder\test1\"
set myArray[1]="C:\testFolder\test1\"

To do that, I initiated a variable to count the number of files.

set /a filesCount=0

then I create loops to iterate over the array

for %%v in (0, 1, 1) do (
   for /r %myArray[%v%]% %%i in (*.*) do (
       set filesCount+=1
   )
   echo %filesCount%
)

In my first folder, I have 1 file but the program systematically returns me 0 for the variable filesCount. I want it to show me 2 for the first folder and 0 for the second.

I try this also:

for %%v in (0, 1, 1) do (
   for /r !myArray[%v%]! %%i in (*.*) do (
       set filesCount+=1
   )
   echo %filesCount%
)

and this:

for %%v in (0, 1, 1) do (
   for /r %myArray[%%v]% %%i in (*.*) do (
       set filesCount+=1
   )
   echo %filesCount%
)
tripleee
  • 175,061
  • 34
  • 275
  • 318
Nelion
  • 3
  • 1
  • 1
    Does this answer your question? [Variables are not behaving as expected](https://stackoverflow.com/questions/30282784/variables-are-not-behaving-as-expected) Specifically, add `setlocal enabledelayedexpansion` to the top of your script and use `!filesCount!` instead of `%filesCount%` (and also `!myArray[%%v]!` instead of `%myArray[%v%]%`). – SomethingDark Apr 27 '23 at 07:50
  • You need `delayedexpansion` [Variables are not behaving as expected](https://stackoverflow.com/questions/30282784/variables-are-not-behaving-as-expected) `for %%v` should be `for /L %%v` to have `%%v` start at 0 end at 1 step 1. As you have it, `%%v` will be assigned `0`, `1` and `1`. `%v%` is the value of variable `v`. `%%v` is the value of the `metavariable` (loop-control variable) `%%v`. I believe that `for /r` does not recognise a variable as the start-directory. To avoid problems, preferred syntax is `set "var=value"` with no terminal spaces or backslashes. – Magoo Apr 27 '23 at 07:57
  • Bash is completely separate from the batch interpreter on Windows, which is called CMD. – tripleee Apr 27 '23 at 07:57

1 Answers1

0
@ECHO Off
SETLOCAL ENABLEDELAYEDEXPANSION

set "myArray[0]=u:\testFolder\test1"
set "myArray[1]=u:\testFolder\test2"
SET /a total=0

FOR /L %%v IN (0,1,1) DO (
 SET /a count=0
 PUSHD "!myArray[%%v]!"
 FOR /r %%i IN (*.*) DO (
  SET /a count+=1
 )
 popd
 SET /a total+=count
 ECHO !count! files IN !myArray[%%v]! total !total!
)
ECHO total is %total%

GOTO :EOF

Note that I've changed the directory names to suit my system.

pushd changes to the nominated directory; popd returns to the directory current when the matching pushd was executed.

Note that delayedexpansion syntax (!var!) is used where the variable changes within the loop and to force the expression myArray[%%v] to be evaluated before the value is used.

set /a always uses the run-time value of variables.

Magoo
  • 77,302
  • 8
  • 62
  • 84