Skip to content

Instantly share code, notes, and snippets.

@sharunkumar
Last active April 23, 2025 12:23
Show Gist options
  • Select an option

  • Save sharunkumar/8caf903c146cbcc4c341571a6c6562df to your computer and use it in GitHub Desktop.

Select an option

Save sharunkumar/8caf903c146cbcc4c341571a6c6562df to your computer and use it in GitHub Desktop.
Windows Batch script for getting the size of the folder in bytes. Usage: folder-size "<directory>"
@echo off
setlocal ENABLEDELAYEDEXPANSION
set firstline=.
set secondline=.
@FOR /F "tokens=1 delims=^^" %%G IN ('dir /s /a "%~1"') DO (
set firstline=!secondline!
set secondline=%%G
)
echo !firstline!
@steve6375

steve6375 commented Apr 23, 2025

Copy link
Copy Markdown

many thanks - here is a script to get four largest folders using your script


@echo off
setlocal ENABLEDELAYEDEXPANSION

:: Set the directory to process
set "DIRECTORY=K:\_ISO\Windows"

:: Temporary file to store folder sizes
set "TEMP_FILE=%TEMP%\dir_sizes.txt"
del "%TEMP_FILE%" 2>nul

:: Iterate over each subdirectory in the given directory
for /d %%A in ("%DIRECTORY%\*") do (
    set "folder=%%A"
    
    echo Processing folder: %%A

    :: Capture the total size from 'dir /s' output
    set firstline=
    set secondline=
    for /f "tokens=*" %%G in ('dir /s /a "%%A" 2^>nul') do (
        set firstline=!secondline!
        set secondline=%%G
    )

echo !firstline!

    :: Extract the folder size from the first line (firstline)
    for /f "tokens=3" %%C in ("!firstline!") do (
        set "size=%%C"
    )

    :: If the folder has a valid size, pad the number with leading zeros and save it to the temporary file
    if defined size (
        :: Remove commas from size string
        set "size=!size:,=!"
        :: Pad the size to ensure consistent length (18 digits)
        set "padded_size=000000000000000000!size!"
        set "padded_size=!padded_size:~-18!"

        echo !padded_size! %%A >> "%TEMP_FILE%"
    ) else (
        echo No size captured for %%A
    )
)


:: type "%TEMP_FILE%"

:: Print the contents of the temporary file to verify the sizes before sorting
echo Listing the 4 largest folders...
set count=0
for /f "tokens=1,* delims= " %%C in ('sort /r "%TEMP_FILE%"') do (
    set /a count+=1
    echo %%D
    if !count! geq 4 (
        goto :cleanup
    )
)

:cleanup
:: Clean up the temporary file
del "%TEMP_FILE%" 2>nul

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment