Not only does this code randomly open a file anywhere within the folder hierarchy, it is also more efficient than the original:
@echo off
setlocal
:: Create numbered list of files in a temporary file
set "tempFile=%temp%\%~nx0_fileList_%time::=.%.txt"
dir /b /s /a-d %1 | findstr /n "^" >"%tempFile%"
:: Count the files
for /f %%N in ('type "%tempFile%" ^| find /c /v ""') do set cnt=%%N
call :openRandomFile
:: Delete the temp file
del "%tempFile%"
exit /b
:openRandomFile
set /a "randomNum=(%random% %% cnt) + 1"
for /f "tokens=1* delims=:" %%A in (
'findstr "^%randomNum%:" "%tempFile%"'
) do start "" "%%B"
exit /b
By default the script will look for files under the current directory, but you can pass a root path as the first argument, and it will start looking there instead.
The code is more efficient when opening just one file, but it really shows improvement if you want to open multiple files, since it only needs to generate the list once. It is also more efficient to let FINDSTR find the selected file instead of looping through the entire list.
I structured the code to make it easy to open multiple random files. Below I randomly select 25, and print out the command to open them. Simply remove the ECHO to actually open the files:
@echo off
setlocal
:: Create numbered list of files in a temporary file
set "tempFile=%temp%\%~nx0_fileList_%time::=.%.txt"
dir /b /s /a-d %1 | findstr /n "^" >"%tempFile%"
:: Count the files
for /f %%N in ('type "%tempFile%" ^| find /c /v ""') do set cnt=%%N
:: Open 25 random files
for /l %%N in (1 1 25) do call :openRandomFile
:: Delete the temp file
del "%tempFile%"
exit /b
:openRandomFile
set /a "randomNum=(%random% %% cnt) + 1"
for /f "tokens=1* delims=:" %%A in (
'findstr "^%randomNum%:" "%tempFile%"'
) do echo start "" "%%B"
exit /b
Best Answer
How do I select a random file in a folder?
Use the following batch file:
The environment variable
!_randomfile!
will contain the filename of a random file.Notes:
/s
if you don't want to match files in subfolders.0
=<%RANDOM%
<32767
so it won't work if you have more than32766
matching files.Further reading
%RANDOM%
that can be used to generate random numbers.