Powershell | Random-Movie-Script to exclude sub folders or limit depth

Viewed 66

So I found this script on google to open and play a random movie in my movie folder. I have the script in the main movie folder, and all the movies are in subfolders in this folder. In those specific movie folders are the movie files and sometimes another folder with extras and featurettes.

The problem I am encountering is, that the script opens up Extras and Featurettes video files that I have with the movies in said subfolder.

This is the script I am running.

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

The shortcut command is

 -executionpolicy bypass -File "F:\1. Movies\somefilename.ps1"

I'm an absolute noob, but I had a look around and "-depth" doesn't work for me since the -include command and -exclude doesn't seem to work because of recursing.

If you could help me modify the code so it only goes down 1 folder deep OR excludes folders named "Extras" and/or "Featurettes" that would be awesome!

I really don't care how clean the code is as long as it works since its just for me.

Thank you guys!

Cheers Fabian

1 Answers
gci ... | Where {
    -not(
        $_.FullName.Contains("\Features\") -or
        $_.FullName.Contains("\Extras\") -or
        $_.FullName.Contains("\Whatever\")
    )
} | Get-Random -Count 1 | Invoke-Item

Note that this calls the .NET String.Contains() method, and this is case-sensitive, as opposed to PowerShell's normal behavior.

If you want case-insensitive matching, either use -match + a regular expression, or $_.FullName.ToLower().Contains("lower case string").


For the sake of completeness, a "pure native" PowerShell variant of the above could look like

gci ... | Where FullName -notmatch "\\(Features|Extras|Whatever)\\" | Get-Random -Count 1 | Invoke-Item

But unless you're familiar with regular expressions, the more explicit variant seems preferable.

Related