I have a folder with N files in it. I'm trying to figure out how to do the following:
Display a list of the files with numbers next to them for selection:
01 - FileA.pdf
02 - FileB.pdf
03 - FileC.pdf
...
Then, have the user select which file he wants to use by typing in the corresponding number. I have no idea where to even begin with this one.
The following batch script should do what you want, the explanation follows below:
@ECHO OFF
SET index=1
SETLOCAL ENABLEDELAYEDEXPANSION
FOR %%f IN (*.*) DO (
SET file!index!=%%f
ECHO !index! - %%f
SET /A index=!index!+1
)
SETLOCAL DISABLEDELAYEDEXPANSION
SET /P selection="select file by number:"
SET file%selection% >nul 2>&1
IF ERRORLEVEL 1 (
ECHO invalid number selected
EXIT /B 1
)
CALL :RESOLVE %%file%selection%%%
ECHO selected file name: %file_name%
GOTO :EOF
:RESOLVE
SET file_name=%1
GOTO :EOF
First of all this script uses something like an array to store the file names. This array is filled in the FOR
-loop. The loop body is executed once for each file name found in the current directory.
The array actually consists of a set of variables all starting with file
and with a number appended (like file1
, file2
. The number is stored in the variable index
and is incremented in each loop iteration. In the loop body that number and the corresponding file name are also printed out
In the next part the SET /P
command asks the user to enter a number which is then stored in the variable selection
. The second SET
command and the following IF
are used to check if the entered number will give a valid array index by checking for a fileX
variable.
Finally the RESOLVE
subroutine is used to copy the content of the variable formed by file
+ the entered number in selection
to a variable named file_name
that can then be used for further processing.
Hope that gives some hints.