Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
518 views
in Technique[技术] by (71.8m points)

windows - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:emp" > C:folderList.txt

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...