5
\$\begingroup\$

I have written a powershell script that will scan a directory for any *mkv, *.mp4, *.avi files, and will parse the filename to get Name, Season Number, Episode number. Then will check against destination directory to determine

  1. If Name exists (if not create it)

  2. If season number exists (if not create it)

  3. Once both these checks have been performed move the file to the destination dir

This syntax works for my purpose, but it is slow... I am lower than a beginner when it comes to powershell (is there such a thing?) - And would like any helpful hints or code mods that the more experienced programmers can provide.

$fileDirectory = "C:\Test\"

foreach ($file in Get-ChildItem $fileDirectory | where {($_.extension -eq '.mkv') -or ($_.extension -eq '.avi') -or ($_.extension -eq '.mp4')}){
    #Setting parent dir to check
    $ParentDir = "\\C:\TV Shows\"

    #setting param to split
    $parts =$file.Name -split '\.'

    #capturing variables
    $ShowName = $parts[0].Trim()
    $SeasonNumber = $parts[1].substring(0,3)
    $EpisodeNumber = $parts[1].substring(3,3)

    #Converting numeric season value to text
    switch ($SeasonNumber){
     S01 
     {
        $SeasonNumber = "Season 01";
        break
     }
     S02 
     {
        $SeasonNumber = "Season 02"
        break
     }
     S03
     {
        $SeasonNumber = "Season 03"
        break
     }
     S04
     {
        $SeasonNumber = "Season 04"
        break
     }
     S05
     {
        $SeasonNumber = "Season 05"
        break
     }
     S06
     {
        $SeasonNumber = "Season 06"
        break
     }
     S07
     {
        $SeasonNumber = "Season 07"
        break
     }
     S08
     {
        $SeasonNumber = "Season 08"
        break
     }
     S09
     {
        $SeasonNumber = "Season 09"
        break
     }
     S10
     {
        $SeasonNumber = "Season 10"
         break
     }
     default {"Something else happened"; break}
     }
    #Setting path variables
    $ShowDir = Join-Path -Path $ParentDir -ChildPath $ShowName
    $SeasonDir = Join-Path -Path $ShowDir -ChildPath $SeasonNumber

    #Write-Host "$ShowDir\"
    #Write-Host $SeasonDir

    #Checking if Show already has a folder
    if (!(Test-Path "$ShowDir\" -PathType Container)) {
        New-Item -ItemType Directory -Force -Path "$ShowDir\"
    }

    #Checking if directory already has folder
    If(!(Test-Path "$SeasonDir\" -PathType Container))
    {
        #if it does not create it
        New-Item -ItemType Directory -Force -Path $SeasonDir
    }

    Move-Item -Path $file.FullName -Destination $SeasonDir
} 
\$\endgroup\$
0

1 Answer 1

5
\$\begingroup\$
  1. Get-ChildItem -include *.ext1, *.ext2 instead of Where
  2. Use pipelining via | (in direct fashion, that is without storing the results in intermediate variables) instead of foreach statement so that the processing starts immediately without waiting for the entire directory to be enumerated first (or use the advanced method of non-blocking IO.DirectoryInfo enumeration in a foreach statement).
  3. Join-Path 'dir' * to construct the path for Get-ChildItem instead of relying on the trailing backslash
  4. -LiteralPath instead of -Path, otherwise PowerShell will fail on paths that contain square brackets as it treats [] as a wildcard specifier.
  5. string concatenation instead of switch

And my personal preferences:

  1. Use regex to split the file name - it'll make the structure more obvious (if you know regex)
  2. Use mkdir instead of New-Item -ItemType Directory (I think it's overly verbose to the point of being obfuscatingly so)
  3. Simply create the directory without checking its existence: the operating system does it anyway, and the code is less "noisy" this way.

$fileDirectory = "C:\Test"
$ParentDir = "c:\TV Shows"

Join-Path $fileDirectory * | Get-ChildItem -include *.mkv, *.avi, *.mp4 | ForEach {
    if ($_.BaseName -notmatch '^\s*(.*?)\s*\.S(\d\d)E(\d\d)') {
        return
        # return is used because we're in a function-like ScriptBlock context
    }
    $ShowDir = Join-Path $ParentDir ($matches[1])
    $SeasonDir = Join-Path $ShowDir ('Season ' + $matches[2])
    # $matches is an internal object set automatically by -match or -notmatch operator

    mkdir $ShowDir -Force >$null
    mkdir $SeasonDir -Force >$null
    # mkdir outputs the directory object so we ignore it

    Move -LiteralPath $_.FullName -Destination $SeasonDir
}
\$\endgroup\$
6
  • \$\begingroup\$ Everything is being copied over to the 1st $ShowDir & $SeasonDir that is scanned. For some reason that is not changing when the next file in the $fileDirectory is processed. See screenshot ![Issue.jpg](postimg.org/image/66ze6xz0v) \$\endgroup\$ Feb 10, 2017 at 21:26
  • \$\begingroup\$ I have added Write-Host to see the $_.BaseName and Write-Host to see $ShowDir & $SeasonDir and the $_.BaseName changes every file but the other two variables do not. See screenshot ![Issue.jpg](postimg.org/image/66ze6xz0v) \$\endgroup\$ Feb 10, 2017 at 21:32
  • \$\begingroup\$ It works for me and I can't see anything in the code that may produce the weird output from your screenshot: the file name starts with Arrow but the output is 12 Monkeys. \$\endgroup\$
    – wOxxOm
    Feb 10, 2017 at 22:00
  • \$\begingroup\$ Try updating PowerShell to the recently released 5.1 version. \$\endgroup\$
    – wOxxOm
    Feb 10, 2017 at 22:12
  • \$\begingroup\$ something wonky was going on with my Powershell ISE. I closed it re-opened it and tried the code again, and it is SO much faster! Sorry for thinking there was a hiccup in the code above. This is excellent \$\endgroup\$ Feb 10, 2017 at 22:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.