2

I am looking to recurse through folders/subfolders/etc. & populate an array with the folder paths dynamically.

Example: I have a folder called "A" which has 2 subfolders "B" & "C". "C" has a sub folder "D". So the array would be:

Folder[01]=A
Folder[02]=A/B
Folder[03]=A/C
Folder[04]=A/C/D

Would FOR/ D command work with what I need? If so, how do I take what the loop gets & add it to an array? Has to be in batch unfortunately. Thank you!

Sid
  • 107
  • 4
  • Have you tried anything? please show your code! `for /D` would indeed work, supposing you add switch `/R`... – aschipfl Jul 21 '16 at 19:59

1 Answers1

4

How do I populate an array with the folder paths dynamically.

Use the following batch file (MakeFolderArray.cmd):

@echo off
setlocal enabledelayedexpansion
rem get length of %cd% (the current directory)
call :strlen cd _length
set /a _index=1
for /d /r %%a in (*) do (
  set _name=%%a
  rem remove everything from the drive root up to the current directory, 
  rem which is _length chars
  call set _name=!!_name:~%_length%!!
  rem replace \ with /
  set _name=!_name:\=/!
  set Folder[0!_index!]=!_name!
  set /a _index+=1
  )
set /a _index-=1
for /l %%i in (1,1,%_index%) do (
  echo Folder[0%%i]=!Folder[0%%i]!
  )
endlocal
goto :eof

:strLen  strVar  [rtnVar]
setlocal disableDelayedExpansion
set len=0
if defined %~1 for /f "delims=:" %%N in (
  '"(cmd /v:on /c echo(!%~1!&echo()|findstr /o ^^"'
) do set /a "len=%%N-3"
endlocal & if "%~2" neq "" (set %~2=%len%) else echo %len%
exit /b

Example:

F:\test>MakeFolderArray
Folder[01]=/A
Folder[02]=/A/B
Folder[03]=/A/C
Folder[04]=/A/C/D

Credits:

Thanks to dbenham for the strlen code from this answer (which works if the string contains \ characters).


Further Reading

  • An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.
  • dir - Display a list of files and subfolders.
  • for /l - Conditionally perform a command for a range of numbers.
  • for /d - Conditionally perform a command on several Directories/Folders.
  • set - Display, set, or remove CMD environment variables. Changes made with SET will remain only for the duration of the current CMD session.
  • variable edit/replace - Edit and replace the characters assigned to a string variable.
  • variables - Extract part of a variable (substring).
DavidPostill
  • 7,734
  • 9
  • 41
  • 60