批处理文件以计数子目录中的文件

批处理文件以计数子目录中的文件

本文介绍了批处理文件以计数子目录中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取此批处理文件以计算子目录中的文件并显示总文件和目录.但是,我对语法不熟悉.

I would like to get this batch file to count the files in the subdirectories and display the total files and directories. However, I'm not familiar with the syntax.

@ECHO OFF
SET "rootpath=C:\Users\RX\Documents\01.00 Meters\100\EMC\EMC 15Aug2016 Level4\res"
SET tcnt=0
FOR /D %%D IN ("%rootpath%\*") DO (
  SET cnt=0
  FOR /F %%K IN ('DIR /A-D /S "%%D" 2^>NUL ^| FIND "File(s)" ^|^| ECHO 0') DO (
    SET /A cnt+=%%K
  )
  SETLOCAL EnableDelayedExpansion
  ECHO %%D: !cnt!
  tcnt+=%%cnt
  ENDLOCAL
)
ECHO !tcnt!
cmd /k

推荐答案

这是一种使用递归的方法.

Here's an approach that uses recursion.

它来自编程而不是 sys admining ;它使用一个函数(与 batch 等效的是 label ),以文件夹为参数,将该文件夹中的文件号求和为全局变量,然后为每个子文件夹调用自身(每次调用都会增加文件夹号).

It comes from programming rather than sys admining; it uses a function (the batch equivalent is a label) that takes a folder as an argument, sums the file number in that folder to a global variable, and then calls itself for each sub-folder (with each call increments the folders number).

@echo off
setlocal enableextensions, enabledelayedexpansion

set _FOLDER="C:\Temp"
set /a _FILES=0
set /a _DIRS=0

call :handle_dir %_FOLDER%
echo Dirs: %_DIRS%, Files: %_FILES%
goto :eof

:handle_dir
    set /a _DIRS=%_DIRS%+1
    for /f %%f in ('dir /b /a:-d "%~1" 2^>nul') do (
        set /a _FILES=!_FILES!+1
    )
    for /f %%f in ('dir /b /a:d "%~1"') do (
        call :handle_dir "%~1\%%f"
    )
    goto :eof

只需将_FOLDER变量设置为要计算其文件和子目录的文件夹.

Simply set the _FOLDER variable to the folder that you want its files and subdirs counted.

注意:在包含大量文件和子文件夹的文件夹上,它可能会产生 StackOverflow :).

Note: On a folder containing tons of files and subfolders, it might yield StackOverflow :) .

这篇关于批处理文件以计数子目录中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 14:54