0

I have a script that counts the number of pages in a PDF unfortunantly it's limited to whatever folder you place it in. I was wonder what I would need to add in order to give the user the ability to select what directory to go to, Is this even possible.

I know how to prompt a user for input just unsure of how to properly implement it here...

Code Sample:

@echo off
set total=0
for %%a in (*.pdf) do (
   title %%a
   for /f "tokens=2 delims=: " %%b in ('pdftk "%%a" dump_data ^| find "NumberOfPages"') do (
      set /a total+=%%b
   )
)
echo %total%  
pause
Nick
  • 49
  • 5
  • possible duplicate of [In Windows cmd, how do I prompt for user input and use the result in another command?](http://stackoverflow.com/questions/1223721/in-windows-cmd-how-do-i-prompt-for-user-input-and-use-the-result-in-another-com) – Marc B Aug 05 '15 at 14:30
  • No it's quite different. I know how to prompt a user for input, just unsure of how to implement it into that code. – Nick Aug 05 '15 at 14:31

1 Answers1

1

Use batch parameters to modify your for loop.

for %%a in (%1/*.pdf) do {

edit: So if the first parameter is "/Documents/work" then the script will see the for loop as:

for %a in (/Documents/work/*.pdf) do {
 ...

Don't forget to handle the use-case where there are no arguments.

Another, less reliable option

Use pushd/popd to get to the directory the user wants to process.

This method is unreliable because it will give unexpected results if the directory is mistyped or doesn't exist.

  1. Temporarily change directory to the target specified by the user

    pushd %1
    
  2. Use the original for loop

    for %%a in (*.pdf) do {
     ...
    }
    
  3. Return to original directory

    popd
    
BryanH
  • 5,826
  • 3
  • 34
  • 47
  • Bryan, Thanks for the quick response but I'm still unsure how that would redirect to what the user inputs as the desired directory they wish to have files counted in. – Nick Aug 05 '15 at 14:34
  • @Nick The for loop will search the directory specified in the script's first parameter `(%1/*.pdf)`. – BryanH Aug 05 '15 at 14:43
  • Bryan. You sir, Are a genius. Using script arguments you suggested I got this to work. Thanks again! – Nick Aug 05 '15 at 14:52
  • You should use round parentheses `()` in batch rather than curly ones `{}`. Moreover, using `pushd .` followed by `cd /D %1` is more robust in case of non-existent directory `%1` (so `popd` always restores the former directory). – aschipfl Aug 05 '15 at 15:19
  • Bryan, new issue, if a user enters a directory that holds multiple directories it only reads the root, anyway to make it read every directory in the root entered by the user? – Nick Aug 05 '15 at 15:29
  • @Nick New issue = new question :) Please make a new question so others can see it and help and learn. – BryanH Aug 05 '15 at 15:32
  • Unfortunately I can only ask once every 90 minutes :/ – Nick Aug 05 '15 at 15:43