How to list all folder with size via batch file

For each folder in the list, use dir command to retrieve the size of the files under the folder

@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
    )

    endlocal

It iterates over the indicated folder (passed as parameter to the batch file, or current directory if there is no paramter).

For each folder inside it (for /d) a recursive dir command is executed inside the inner for command, and from its output, the summary line at the end (extracted by findstr) is parsed (the tokens in for command) and the total size of all the files under this subfolder is retrieved. Then the name (and extension if it has) of the folder and the size of the elements under it is echoed to console.

If a file needs to be created, redirect the output of the batch to a file

getSizes.cmd "c:\temp" > C:\folderList.txt

Leave a Comment