windowswindows-8command-linedir

Windows Dir command - order subdirectories by size


How could I display the subdirectories of a folder from largest to smallest using the dir command?

I've tried using dir /O:-S command, and although it sorts files just fine, it doesn't seem to order the subdirectories.

Ideally, the command should be able to go down several levels; some of these sub-folders have their own folders. For example:

D:/
|-- Folder 1
    |-- Subfolder 1
    +-- Subfolder 2
        |--Another folder
+-- Folder 2

Suppose the total size of Folder 1 (including all files in its subfolders) is 10GB, and that of Folder 2 is 15GB, how would I output their order sorted by total content size?

I.e.

94932485 Folder 2
6453445  Folder 1

Thanks in advance!


Solution

  • This seems to work for the changed requirements: alter c:\folder to the folder level you want to query.

    @echo off
    pushd "c:\folder"
    for /f "delims=" %%a in (' dir /ad /b ') do call :size "%%~fa"
    sort /r < "%temp%\dirsize.tmp"
    del "%temp%\dirsize.tmp"
    popd
    pause
    goto :eof
    
    :size
    for /f "tokens=3" %%b in ('dir /s "%~1" 2^>nul ^|find " File(s) "') do set "n=%%b"
    set dirsize=%n%
    REM set dirsize=%dirsize:,=%
    set dirsize=                 %dirsize%
    set dirsize=%dirsize:~-18%
    >>"%temp%\dirsize.tmp" echo %dirsize% "%~1"