Computing Staff
  • 10

Create Batch File To Randomly Open File

  • 10

I need to create a batch file that opens a random file from a text file containing numerous filepaths.
The list reads as following:
C:/Pictures/asda.jpg
C:/Music/adsf.wav
C:/Documents/sdgafg.txt
etc….
Can anyone help me figure this out please?

Share

1 Answer

  1. Am I confused about what you want to achieve?

    You stated I need to create a batch file that opens a random file from a text file from which I took it that you wanted to open any file at random from a list of files. The %random% variable is used to generate a random number within a range, that number will be used to identify which line the filename to be opened exists on in the text file. The line number will change every time the script is run (almost) therefore a new random file will be opened each time.

    The script produced can be used with any file which contains filenames where the extension is associated with a program which will open it.

    Here’s a random number generator which will display random numbers in the range 1 thru’ 42 (as if 42 was the number of lines in the text file)

    @echo off
    
    setlocal 
    
    set lines=42
    
    :loop
    set /a file=%random% %% %lines%+1
    if %file% lss 10 set file= %file%
    echo The file shown on line %file% of the text file will be selected
    
    set /a cnt+=1
    if %cnt% gtr 20 (exit /b
       ) else (
         goto loop
    )
    
    

    Obviously the script is incomplete and needs coding added to count the number of lines in the text file and to open the appropriate file.

    Please come back & tell us if your problem is resolved.

    • 0