Daniel Johnston
Daniel Johnston

Reputation: 113

Counting files using a batch file

I tried the following code in a .bat file to count the number of files in a directory:

for /f %%a in ('dir /A-D /B /S | find /C /V ""') do set FILECOUNT=%%a
echo %FILECOUNT%
pause

However, it doesn't work and doesn't even pause. It instead flashes something like ": was unexpected at this time". If I just write

dir /A-D /B /S | find /C /V ""
pause

It works fine and displays the number of files but I want to save this number into a variable. What am I doing wrong?

Upvotes: 1

Views: 1273

Answers (1)

Dennis van Gils
Dennis van Gils

Reputation: 3452

You need to escape the pipe, so

@echo off
for /f %%a in ('dir /A-D /B /S ^| find /C /V ""') do set FILECOUNT=%%a
echo %FILECOUNT%
pause

Upvotes: 4

Related Questions