Powershell script to open random video

1

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

Posted 2014-12-16T12:12:06.317

Reputation: 13

1Is it faster if you have your video-player of choice open already? If you remove | Invoke-Item, does it complete near instantly? – Jeeva – 2014-12-16T12:51:10.697

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 – 2014-12-16T18:45:35.120

Indeed, it wouldn't. But the writing is near instant? – Jeeva – 2014-12-16T19:12:15.160

No, the writing is still delayed – Per DeDor – 2014-12-16T21:41:51.950

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 – 2014-12-17T09:38:05.197

Answers

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

Posted 2014-12-16T12:12:06.317

Reputation: 3 478

This was really helpful! Delay is now about 5 time better. – Per DeDor – 2014-12-17T20:32:04.930