@ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
FOR /f %%a IN (
'dir /b /a-d "%sourcedir%\*.txt"^|find /i /c ".txt" '
) DO SET /a selection=1 + (%RANDOM% %% %%a)
FOR /f "tokens=1*delims=:" %%a IN (
'dir /b /a-d "%sourcedir%\*.txt"^|findstr /n /i ".txt" '
) DO IF %%a==%selection% SET filename=%%b
ECHO selected %filename%
GOTO :EOF
You would need to change the setting of sourcedir
to suit your circumstances.
find /c
counts the number of files found by the dir
command and the for
assigns the count to %%a
. selection
is then assigned to 1+(randomnumber mod filecount) giving 1..filecount.
findstr /n
outputs the name of each file found by the dir
command, prefixed by a sequential number : %%a will be assigned the number (token before the :
and %%b
the filename (afther the first delimiter where delims is :
)
When the line number matches selection
, filename is assigned the filename found.