Windows – How to select a random file in a folder

batch filecommand linewindows

I am trying to select a random file of a specific type like *.mp4
from a folder (and optionally subfolders) using the Windows command line batch script (no PowerShell)

The file full path should be stored in a environment variable for further use

How can I achieve this?

Best Answer

How do I select a random file in a folder?

Use the following batch file:

@echo off
setlocal
setlocal EnableDelayedExpansion
rem store the matching file names in list
dir /b *.txt /s 2> nul > files
rem count the match files
type files | find "" /v /c > tmp & set /p _count=<tmp 
rem get a random number between 0 and count-1
set /a _random=%random%*(%_count%)/32768
rem we can't skip 0 lines
if %_random% equ 0 (
  for /f "tokens=*" %%i in ('type files') do (
    set _randomfile=%%i
    echo !_randomfile!
    goto :eof
    )
) else (
  for /f "tokens=* skip=%_random%" %%i in ('type files') do (
    set _randomfile=%%i
    echo !_randomfile!
    goto :eof
    )
)

The environment variable !_randomfile! will contain the filename of a random file.

Notes:

  • Remove /s if you don't want to match files in subfolders.
  • 0 =< %RANDOM% < 32767 so it won't work if you have more than 32766 matching files.

Further reading

  • An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.
  • find - Search for a text string in a file & display all the lines where it is found.
  • for /f - Loop command against the results of another command.
  • random - The Windows CMD shell contains a dynamic variable called %RANDOM% that can be used to generate random numbers.