Batch recursing through folders & populating an array

后端 未结 1 1491
猫巷女王i
猫巷女王i 2021-01-15 10:32

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

相关标签:
1条回答
  • 2021-01-15 11:07

    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).
    0 讨论(0)
提交回复
热议问题