2
votes

So I'm going to count files in a directory including all subfolders and get a output as a number of how many files it found within the directory. The problem is I want to exclude all the folders that has the name error. Those files within that folder I do not want to be counted.

Simply...

for /r "\\server\share\folderA" %%G in (*.*) do (
set /A count=count + 1
)    
echo %count%

Under folderA there are plenty of subfolders that I'm counting, but also the "error" folders that I do not want to count.

So I'm trying the following...

Create a temp file called exclude.txt and type error to that file

if not exist "c:\temp" mkdir "c:\temp" 2>nul
if not exist c:\temp\exclude mkdir c:\temp\exclude 2>nul
echo error> %excludefolder%\exclude.txt

Now I want to combine this somehow. Basically do something like this...

for /r "\\server\share\folderA" %%G in (*.*) EXCLUDE: c:\temp\exclude\exclude.txt do (
set /A count=count + 1
)    

But I'm aware this will not work and I'm not sure how to work it out. Does anyone know? Thanks!

2

2 Answers

3
votes

Use DIR /S /B /A-D to iterate all files. The output includes the full path to each file.

Pipe that result to FINDSTR /L /I /V "\\error\\ to filter out paths that contain \error\. This will also exclude any folders within an error folder. The search could be modified to exclude only 'error' but include children of 'error'.

Pipe that result to FIND /C /V "" to count the number of files (lines).

dir /s /b /a-d | findstr /liv "\\error\\" | find /c /v ""

The above will simply display the count.

If you want to capture the count in a variable, then use FOR /F to parse the output of the above command. Unquoted poison characters like | must be escaped when used in FOR /F.

@echo off
for /f %%N in ('dir /s /b /a-d^|findstr /liv "\\error\\"^|find /c /v ""') do set count=%%N
echo count=%count%
2
votes

You can exclude from count the folder containing the string "error" :

@echo off
set count=0

for /r "\\server\share\folderA" %%a in (*.*) do (
  echo %%~pa | find /i "error" || set /A count+=1
)    
echo %count%

It's a good way if you sure that you just have ONE Error folder. If you have another folder containing the string "error" it will be excluded too from count.