How to count files in a folder

2019-06-09 10:13发布

When I use cmd to count the files in a folder, the following set of codes give different results. Can you show me a correct method?

 @echo off
setlocal EnableDelayedExpansion
set aa=0
for %%s in ("F:\*.*") do (
        set /a aa=!aa!+1        
)
echo !aa!

set aa=0
 for %%s in ("F:\*.*") do (
     set /a aa=!aa!        
)
echo !aa!
endlocal

set aa=0
for %%s in ("F:\*.*") do (
      set /a aa=%aa%+1        
)
echo %aa%

set aa=0
for %%s in ("F:\*.*") do (
       set /a aa=%aa%       
)
echo %aa%

pause

标签: cmd
2条回答
做个烂人
2楼-- · 2019-06-09 10:53

These two snippets will count the visible files in F:\

@echo off
setlocal EnableDelayedExpansion
set aa=0
for %%s in ("F:\*.*") do (
        set /a aa+=1        
)
echo !aa!

For the case above, you can also use this:

@echo off
set aa=0
for %%s in ("F:\*.*") do (
        set /a aa+=1        
)
echo %aa%
查看更多
走好不送
3楼-- · 2019-06-09 11:06

Here is a much faster solution. Use DIR /B to list the files, piping the result to FIND /C to count the number of entries. The following will give the same result as the foxidrive solution.

@echo off
dir /b /a-d-h-s ^| find /c /v ""

The /a-d-h-s option excludes directories, hidden files, and system files. Use /a-d if you want to include hidden and system files.

The /v "" is an arcane way to cause FIND to match any value.

If you need to define a variable with the count, then use FOR /F to capture the result.

@echo off
for /f %%N in ('dir /b /a-d-h-s ^| find /c /v ""') do set count=%%N
echo %count%
查看更多
登录 后发表回答