Search code examples
filebatch-filedir

How Does This Code Work? (windows batch)


@echo off
setlocal disabledelayedexpansion

set "folder=%~1"
if not defined folder set "folder=%cd%"

for /d %%a in ("%folder%\*") do (
    set "size=0"
    for /f "tokens=3,5" %%b in ('dir /-c /a /w /s "%%~fa\*" 2^>nul ^| findstr /b /c:"  "') do if "%%~c"=="" set "size=%%~b"
    setlocal enabledelayedexpansion
    echo(%%~nxa # !size!
    endlocal
)

pause

I read this on the site and it works just fine, but I'm trying to incorporate it into my own code, however whenever I modify it, it just doesn't work. Someone please explain it to me so I can use it for myself.


Solution

  • set "folder=%~1"
    if not defined folder set "folder=%cd%"
    

    Get the indicated folder passed as argument or if no argument is present, use current folder

    for /d %%a in ("%folder%\*") do (
    

    for each folder under the indicated one

    for /f "tokens=3,5" %%b in ('
        dir /-c /a /w /s "%%~fa\*" 2^>nul ^| findstr /b /c:"  "
    ') do if "%%~c"=="" set "size=%%~b"
    

    execute a recursive dir command of all the contents of the indicated folder, searching the lines that start with two blank spaces, that is, the footer lines of the dir command. There are two lines, one with 4 tokens and one with five tokens. We only want the first one, that is, the line with 4 tokens, the line with the size of all the files under the folder.

    As for each folder (it is a recursive dir) there will be a footer line, we are only interested in the last one, so we keep storing the size value (the third token in the line) in the size variable. That way, at the end, the variable will contain the final total of the listing.

    setlocal enabledelayedexpansion
    echo(%%~nxa # !size!
    endlocal
    

    As we are working inside a block of code, to retrieve the changed value in the variable we need delayed expansion to echo the size variable, along with the name and extension of the folder being iterated.