Search code examples
for-loopdos

Get Random File Order in Dos FOR Command


Here is DOS

FOR /R folder %%f in (*.filetype) DO something

I like to achieve, when each time run this, random file order will be feed to something from FOR loop


Solution

  • The trick here is to record the file names prefixed by a random numeric key in a temporary file, sort the lines by their random keys and then extract the file names in their new order. This can be accomplished with the DOS commands type and sort like this:

    @echo off
    setlocal enabledelayedexpansion
    set tempfile=_%RANDOM%_%RANDOM%_%RANDOM%_.tmp
    type nul >%tempfile%
    for /R folder %%i in (*.filetype) do set key=!RANDOM!!RANDOM!!RANDOM!000000000000& echo !key:~0,15!%%i>> %tempfile%
    for /F "tokens=*" %%i in ('type %tempfile% ^| sort') do set line=%%i&set file=!line:~15!&something
    del %tempfile%
    

    Notice that the tokens folder and filetype in your example are on the first for-line (where the writing to the temporary file is done), while something is on the next line. instead of something, you could write here for example echo !file! to print the file names to the console.