简体   繁体   中英

How to check if a folder has more than 20 files in it in batch?

I want to write an batchfile that Deletes a folder if the folder has more than 20 files in it. but I do not know how to do it.

I use Windows7 Ultimate.

List the files in bare format and use find command to count the number of output lines

set "nFiles=0"
for /f %%a in (
    'dir /a-d /b "c:\folder\*" 2^>nul ^| find /c /v ""'
) do set "nFiles=%%a"
echo %nFiles%

List the files in usual format and use findstr to locate the line/field with the number of files

set "nFiles="
for /f %%a in (
    'dir "c:\folder\*" ^| findstr /b /c:"  "'
) do if not defined nFiles set "nFiles=%%a"
if not defined nFiles set "nFiles=0"
echo %nFiles%

Use a counter over the output of dir command

set "nFiles=0"
for /f %%a in ('dir /b /a-d "c:\folder\*" 2>nul ') do set /a "nFiles+=1"
echo %nFiles%

Or you can use wmic , or number the lines in the output of dir command with the usage of findstr /n , or ....

In any case

if %nFiles% gtr 20 rd /s /q "c:\folder" 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM