powershell script for transcoding videos

Basically:

  • skips any directory ending with x264
  • excludes all files named x265
  • transcodes .mov files to .x265.mp4 using ffmpeg with crf=22



ffmpeg command is:

ffmpeg -hide_banner -i "$file" -c:a copy -c:v libx265 -x265-params crf=22:pools=2:frame-threads=1 -movflags +faststart -n "$newFile"


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
$filteredDirs = gci -Dir -Force | ? Name -NotLike '*x264' | Select-Object
foreach ($dir in $filteredDirs)
{
    Write-Host "`nProcessing files from following directories:`n$dir"

    $counter = 0
    $srcFiles = gci $dir -r *.mov -exclude *x265*

    if($srcFiles.count -le 0){ continue }

    $startTime = $(get-date)
    Write-Host "`nSource srcFiles, cmd: gci -r *.mp4 -exclude *x265*"
    $srcFiles | measure Length -Sum

    foreach ($file in $srcFiles)
    {
        $newFile = [io.path]::ChangeExtension($file, '.x265.mp4')
        if(Test-Path $newFile -PathType leaf){ continue }

        Write-Host "`n"
        $counter = $counter + 1

        ffmpeg -hide_banner -i "$file" -c:a copy -c:v libx265 -x265-params crf=22:pools=2:frame-threads=1   -movflags +faststart -n "$newFile"

        if($counter % 20 -eq 0) {timeout /t 30}
    }

    $elapsedTime = $(get-date) - $startTime
    $totalTime = "{0:HH:mm:ss}" -f ([datetime]$elapsedTime.Ticks)
    Write-Host "`n`nEncoded files in $totalTime"

    Write-Host "`n`nSource srcFiles, cmd: gci -r *.mp4 -exclude *x265*"
    $srcFiles | measure Length -Sum

    Write-Host "Encoded files, cmd: gci -r *.x265.mp4"
    $dstFiles = gci $dir -r *.x265.mp4
    $dstFiles | measure Length -Sum

    $srcSize = ($srcFiles | measure Length -Sum).Sum
    $dstSize = ($dstFiles | measure Length -Sum).Sum

    $srcSizeMB = [math]::Round($srcSize / 1MB, 3)
    $dstSizeMB = [math]::Round($dstSize / 1MB, 3)

    Write-Host "Source Size: $srcSizeMB MB, Encoded Size: $dstSizeMB MB"
    $compression = $srcSize / $dstSize
    Write-Host "Compression factor: $compression"

    
    $deleteSrcFiles = Read-Host -Prompt "`n`nShould i clean up source srcFiles? (y/n)"
    if($deleteSrcFiles -like "y")
    {
        Write-Host "Deleting source srcFiles"
        $srcFiles | %{rm $_}
    }


    timeout /t 30
}