count folders and subfolders with batch file

2019-06-21 18:31发布

问题:

I am looking to create a batch file that when given a pathway, it will count all the folders and sub folders within it. So far I am only able to gather the number of folders within the 1st level of the pathway. I will then pipe it to a text file.

Here's what I have so far:

for /f %%a in ('dir /b /ad %folder%^|find /c /v "" ') do set count=%%a
echo %count% folder(s^)>> !output!

Am I close to getting what I want? What do I need to tweek?

Thanks!

回答1:

Add /s to include all subfolders:

for /f %%a in ('dir /b /s /ad %folder%^|find /c /v "" ') do set count=%%a
echo %count% folder(s^)>> !output!


回答2:

A small edit of this answer: Batch file to list files and folders in a simple format

@echo off
setlocal disableDelayedExpansion
pushd %1
set "tab=    "
set "indent="
call :listFolder >report.txt
exit /b

:listFolder
setlocal
set "indent=%indent%%tab%"
for /d %%F in (*) do (
  echo %indent%.\%%F
  pushd "%%F"
  call :listFolder
  popd
)
exit /b


回答3:

Here's how I solved the problem.

if exist "File Count" del "File Count"
dir "%~d1%~p1\*.*" /b /s >> "File Count"
find /c "." "File Count"

First we check to see if a file exists, and if so, delete it. Then we get a list of files and dump that to our file. then run FIND on the file. FIND will handily give us a big label, so the name of the file might as well be something attractive and human readable.

I am personally interested in a specific filetype, so I changed . into *.jpg but the principle is the same.