1

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.

Community
  • 1
  • 1
Dave
  • 25
  • 2
  • 6

1 Answers1

1
@echo off

setlocal
cd ..

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

:append
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.

Susam Pal
  • 32,765
  • 12
  • 81
  • 103