Windows CMD script to count files and get filenames
I am not very familiar with Windows CMD scripts and I need to write one that will check the number of files in a specific folder and store the filenames found in variables (maybe an array). Here is what I have (%1 is the folder I am getting as a parameter):
ECHO ### Checking the number of files under %1 ###
for %%x in (%1\pdf*.*) do (
set file[!numFiles!]=%%~nxf
set /a numFiles+=1
)
ECHO ### Number of files found: %numFiles%
for /L %%i in (0,1,2,3,4) do (
echo !file[%%i]!
)
Solution 1:
How do I count the files in a specific folder and store the filenames in an array?
There are a number of problems with your code:
You need to enabledelayedexpansion if you are going to use it later.
You haven't initialised
numFiles
.%%~nxf
should be%%~nfx
.Your for /l command has the wrong syntax (it should be
start,step,end
).
Here is a corrected batch file (test.cmd):
@echo off
setlocal enabledelayedexpansion
ECHO ### Checking the number of files under %1 ###
set numFiles=0
for %%x in (%1\pdf*.*) do (
set file[!numFiles!]=%%~nfx
set /a numFiles+=1
)
ECHO ### Number of files found: %numFiles%
set /a index=%numFiles%-1
for /L %%i in (0,1,%index%) do (
echo !file[%%i]!
)
endlocal
Example usage and output:
> dir *.pdf
Volume in drive F is Expansion
Volume Serial Number is 3656-BB63
Directory of F:\test
21/02/2017 22:53 0 pdf01.pdf
21/02/2017 22:53 0 pdf02.pdf
21/02/2017 22:53 0 pdf03.pdf
3 File(s) 0 bytes
0 Dir(s) 1,701,266,092,032 bytes free
> test .
### Checking the number of files under . ###
### Number of files found: 3
F:\test\pdf01.pdf
F:\test\pdf02.pdf
F:\test\pdf03.pdf
Further Reading
- An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.
- enabledelayedexpansion - Delayed Expansion will cause variables to be expanded at execution time rather than at parse time.
- for - Conditionally perform a command on several files.
- for /l - Conditionally perform a command for a range of numbers.
- parameters - A command line argument (or parameter) is any value passed into a batch script.