Share this page 

Count files in directory and subdirectoriesTag(s): Misc Prog HowTo


Using DIR
[count.cmd]
@echo off
pushd %1
set /A files=0
for /F %%i in ('dir /B /S /A-D .') do set /A files=files+1
popd
echo There are %files% files in %1.
Example
C:\>count "d:\downloads\_ok\_en"
There are 395 files in d:\downloads\_ok\_en.
You can make it more specialized by specifying wildcards. For example, to count only music files :

[countmusic.cmd]

@echo off
pushd %1
set /A files=0
for /F %%i in ('dir /B /S /A-D *.mp3 *.flac *.wav') do set /A files=files+1
popd
echo There are %files% music files in %1.

Using Robocopy
Using robocopy to quickly count the files without the copy operation (/nocopy, see robocopy /? for more details).

[count.cmd]

@echo off
rem count 
rem   return how many if the given directory and subdirectory plus the total count
rem   based on https://stackoverflow.com/a/31199770/25122

setlocal enableextensions disabledelayedexpansion
set "total=0"
pushd %1 && (
  for /f "tokens=1,*" %%a in ('robocopy . . /l /nocopy /is /e /nfl /njh /njs') do (
      echo %%~fb : %%a
      set /a "total+=%%a"
  )
  popd
)
echo Total files: %total%
Example :
C:\>count d:\downloads\_ok\_en
d:\downloads\_ok\_en\ : 388
d:\downloads\_ok\_en\Billie Holiday - Remixed & Reimagined\ : 16
d:\downloads\_ok\_en\Black Sabbath\ : 12
d:\downloads\_ok\_en\Doves\ : 10
d:\downloads\_ok\_en\eminem\ : 18
d:\downloads\_ok\_en\Marilyn Manson - We Are Chaos\ : 10
d:\downloads\_ok\_en\Revolting Cocks - Linger Ficken' Good\ : 10
Total files: 464
To redirect to a file
C:\>count d:\downloads\_ok\_en > filecount.txt