dot
dot

Reputation: 2833

How to open multiple random files with applescript?

I am successfully opening 1 random file, like this:

tell application "Finder"
   open some file of folder "HD:random"
end tell

I would like to open 3 random files in the folder. 3 different ones. If I run the applescript 3 times I will get the same ones sometimes.

Thanks!

Upvotes: 1

Views: 1791

Answers (1)

regulus6633
regulus6633

Reputation: 19030

Here's 1 way using "some file"...

set theNumber to 3
set theFolder to choose folder

set theFiles to {}
repeat
    tell application "Finder" to set aFile to (some file of theFolder) as text
    if aFile is not in theFiles then
        set end of theFiles to aFile
        tell application "Finder" to open file aFile
    end if
    if (count of theFiles) is equal to theNumber then exit repeat
end repeat

Here's another way using random numbers...

set theNumber to 3
set theFolder to choose folder

tell application "Finder" to set theFiles to files of theFolder
set fileCount to count of theFiles
if fileCount is less than theNumber then error "I couldn't find " & (theNumber as text) & " files in the chosen folder."

set randomNumbers to {}
repeat
    set aNum to random number from 1 to fileCount
    if aNum is not in randomNumbers then
        set end of randomNumbers to aNum
        tell application "Finder" to open (item aNum of theFiles)
    end if
    if (count of randomNumbers) is equal to theNumber then exit repeat
end repeat

Upvotes: 1

Related Questions