techthoughts2
3/30/2016 - 2:53 AM

Movie File Sort

It is common when sorting digital movie collections to sort in a directory/movie-file type format where the directory and movie-file share the same name. Example: Godfather/Godfather.mkv This sorting script is capable of scanning an entire directory, and then creating directory folders based off of the movie file name. It will then move the file into the new directory.

#gets all files from specified path. scans each file and gets the BaseName of the file.
#script will create a directory for each BaseName and move the file to that new BaseName directory.
#this can be handy for things like sorting a digital movie collection.
#---------------------------------------------------------
$path = "V:\Movies\Sci-FI Top 50 movies\"
#---------------------------------------------------------
$files = Get-ChildItem -Path $path -Recurse -ErrorAction SilentlyContinue | `
    Where-Object {$_.BaseName -notlike "Thumbs" -and $_.PSIsContainer -eq $false}
#$files #uncomment if you would like to display a list of the files to be moved
foreach ($file in $files) {
    Write-Output "-----------------------------"
    try {
        Write-Output "Checking if " $file.BaseName "DIR exists"
        $newDirPath1 = "$path\" + $file.BaseName
        $newDirPath = "$newDirPath1"
        [boolean]$check = Test-Path -LiteralPath "$newDirPath"
        if ($check -ne $true) {
            New-Item -ItemType Directory $newDirPath -ErrorAction Stop
            Write-Output "New DIR created."
        }
        $check = Test-Path -LiteralPath "$newDirPath"
        if ($check -eq $true) {
            Write-Output $newDirPath "found"

            Write-Output "Moving" $file.Name "to new DIR"
            $originPath = "$path\" + $file.Name
            Write-Output "Origin:" $originPath
            $destPath = "$newDirPath\" + $file.Name
            Write-Output "Destination:" $destPath
            Move-Item -LiteralPath $originPath -destination $destPath -ErrorAction Stop
            Write-Output "File Moved to new DIR"
        }
        else {
            Write-Output $newDirPath "NOT found"
        }
    }
    catch {
        Write-Error $_
    }
}