7739 » How can I determine the size and count of files in a folder from a command prompt or batch? 10-Feb-04
I have scripted SizeCnt.bat to determine the size and count of files in a folder, and optionally in all sub-folders.
The syntax for using SizeCnt.bat is:
SizeCnt Folder [/S]
where Folder is the path to the folder you wish to measure, and /S is an optional switch that will
also include the size and count of the files in all of Folder's sub-folders.
The output is displayed on the CMD console, but you can pipe it to a file using the following syntax:
SizeCnt Folder [/S]>FileName
You can import the size and count into environment variables in your script, as in:
for /f "Tokens=1,2" %%s in ('SizeCnt Folder [/S]') do set /a FldSize=%%s&set /a fileCnt=%%t
SizeCnt.bat contains:
@echo off
setlocal
If {%1}=={} goto Syntax
set folder=%1#
set folder=%folder:"=%
set folder=%folder:\#=%
set folder=%folder:#=%
if not exist "%folder%\*.*" goto Syntax
if {%2}=={} goto begin
set xx= %2
set xx=%xx:"=%
if /i "%xx%" NEQ " /s" goto Syntax
:begin
set /a cnt=0
set /a tot=0
pushd "%folder%"
call :doit>nul 2>&1
popd
@echo %tot% %cnt%
endlocal
exit /b 0
:doit
for /f "Tokens=*" %%s in ('dir /b /as /ah /a-d%xx%') do call :addsize "%%s"
goto :EOF
:Syntax
@echo Syntax: SizeCnt Folder [/S]
endlocal
exit /b 1
:addsize
set /a sz=%~Z1
set /a tot=%tot% + %sz%
set /a cnt=%cnt% + 1
End of Article


*** for /f "usebackq" %%a in (`dir /ad /s /b ^| find /c ":\"`) do set Foldercnt=%%a ***
to the :doit section.
However I've just discovered that it doesn't work if the file or folder structure is larger than 2147483648 bytes (2GB).
If you add a single byte to the stored variable it wraps around to -2147483647 and increases in size until it reaches 2147483648 again when it wraps again.
I've been able to use vbscript to generate the same info but can't find a way to obtain the number of folders.
alunklrodgers September 10, 2008 (Article Rating: