1

I was looking for a way to open random video file in my folder which has about 400 videos (20 videos in 20 subfolders).

I found a powershell script and managed it to work, but every time I run it I takes about 12 seconds to open some file, could you think of some way to make it faster?

My random.ps1 script contect is following:

$formats = @("*.avi","*.mkv")
$dir = Split-Path $MyInvocation.MyCommand.Path
gci "$dir\*" -include $formats -recurse | Get-Random -Count 1 | Invoke-Item

Thank you for your help

Per DeDor
  • 13
  • 1
  • 3
  • 1
    Is it faster if you have your video-player of choice open already? If you remove `| Invoke-Item`, does it complete near instantly? – Jeeva Dec 16 '14 at 12:51
  • If I have video player open already it doesn't improve waiting time and when I removed | Invoke-Item the video will not play, it just writes out the video name to the console. – Per DeDor Dec 16 '14 at 18:45
  • Indeed, it wouldn't. But the writing is near instant? – Jeeva Dec 16 '14 at 19:12
  • No, the writing is still delayed – Per DeDor Dec 16 '14 at 21:41
  • Seems like the delay is on the lookup, though my system is apparently gratifyingly fast. I'd guess you're either looking at a slow drive, or something accessed over the network on another system. The answer below involving caching is close enough to what I was going to suggest next. – Jeeva Dec 17 '14 at 09:38

1 Answers1

2

It's slow because the script has to find all the names of all the videos before it can pick a random one. Searching for all those files takes time. I can't think of an easy way to get around that.

One thing you could do however is to make a pair of scripts. The first one creates a list of the video files and puts it in a file ("videos.txt"):

$formats = @("*.avi","*.mkv")
$dir = Split-Path $MyInvocation.MyCommand.Path
gci "$dir\*" -include $formats -recurse | Set-Content .\videos.txt

And the second script selects a file from videos.txt and plays it:

Get-Content .\videos.txt | Get-Random -Count 1 | Invoke-Item

The first script is slow, but the second one is fast. You could maybe call the first script from Windows Task Scheduler so that videos.txt will be kept up-to-date.

dangph
  • 4,603
  • 4
  • 25
  • 31