Take the 2-minute tour ×

Possible Duplicate:
Batch file - Write list of files to variable

Within a batch file, I'm trying to create a list of all the PDF files in a directory and its subfolders, and store this information in a variable using set.

For example, if parentDirectory contained 1.pdf, 2.pdf, and 3.pdf in itself and its subfolders:

cd parentDirectory
set pdfList =
-code for populating the list goes here-
Now pdfList contains "1.pdf 2.pdf 3.pdf"

Any help would be appreciated.

share|improve this question

marked as duplicate by Eitan T, Robert Harvey Aug 20 '12 at 16:50


1 Answer 1

up vote 1 down vote accepted
@echo off

cd ..

if exist *.pdf(
    for /f "tokens=*" %%a in ('dir /b *.pdf') do call :append %%a
echo pdfList: %pdfList%
goto :eof

if defined pdfList (
    set pdfList=%pdfList% %1
) else (
    set pdfList=%1

This will add the list of PDF filenames separated by spaces to the pdfList variable. If you want to include the PDF filenames in all subdirectories as well, then change the dir command in the for statement to:

dir /s /b *.pdf

But using this will have a side-effect that a list of absolute paths would be added to the pdfList variable, and not relative paths as you expressed in your question.

The first if statement ensures that we execute the dir command only if PDF files are present. We don't want to invoke DIR command if they are not present; otherwise dir would print 'File not found' error.

The :append subroutine is necessary because if we try to append to the pdfList variable in the for statement itself, we'll find that the updated value of pdfList in one iteration doesn't survive till the next iteration.

The if statement in the :append subroutine is to make sure that we do not have a leading space in the value of pdfList.

share|improve this answer
Worked like a charm. Thanks. –  Dave Aug 22 '12 at 21:19
