Batch recursion through folders and filling an array

I am looking for recursion through folders / subfolders / etc. and dynamically populates the array with dynamic folders.

Example: I have a folder called "A" that has 2 subfolders "B" and "C". "C" has a subfolder of "D". Thus, the array will look like this:

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

Will the FOR / D command work with what I need? If so, how can I take what the loop gets and add it to the array? Unfortunately, it must be in the party. Thank!

+2
source share
1 answer

How can I dynamically populate an array with dynamic folders.

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:

dbenham strlen ( , \).


+3

Source: https://habr.com/ru/post/1658856/


All Articles