Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to list all folder with size via batch file

I want a simple solution for list of folders and size of them in either txt or csv format.

I use this code for folder list

dir C:\Temp\*.* /b /a:d > C:\folderList.txt

current output

<<folderList.txt>>
folder1
folder2
folder3

desired output

<<folderList.txt>>
folder1 # 100 MB
folder2 # 30 MB
folder3 # 110 MB

Simply it would generate the size of each folder.. How can I proceed?? any help

like image 435
goldenbutter Avatar asked Feb 11 '14 19:02

goldenbutter


1 Answers

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
like image 89
MC ND Avatar answered Nov 09 '22 22:11

MC ND