Last active
April 9, 2023 19:35
-
-
Save kerray/7ce5b4a38834afcd76a3fd407f7a5ec0 to your computer and use it in GitHub Desktop.
Script that copies and renames subtitle files from the 'Subs' folder to the folder containing the media file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <# | |
| This script copies and renames subtitle files from the 'Subs' folder to the folder containing the media files. | |
| It works recursively through all child folders. | |
| The user can configure the languages, video formats, and subtitle formats to process. | |
| Larger subtitle files are prioritized when multiple files are found for the same language. | |
| #> | |
| # Configuration | |
| $languageMap = @{ | |
| "English" = "en" | |
| "Czech" = "cs" | |
| } | |
| $videoFormats = @("mp4", "avi", "mkv") | |
| $subtitleFormats = @("srt") | |
| function Copy-RenameSubtitles($directory) { | |
| $mediaFiles = Get-ChildItem -Path $directory -Include ($videoFormats | ForEach-Object { "*.$_"}) -Recurse -File | |
| $subsFolder = Join-Path -Path $directory -ChildPath "Subs" | |
| if (Test-Path $subsFolder) { | |
| foreach ($mediaFile in $mediaFiles) { | |
| $mediaFileBaseName = [System.IO.Path]::GetFileNameWithoutExtension($mediaFile.FullName) | |
| foreach ($entry in $languageMap.GetEnumerator()) { | |
| $language = $entry.Key | |
| $languageCode = $entry.Value | |
| $subtitleFiles = Get-ChildItem -Path $subsFolder -Filter "*$language*.srt" -Recurse -File | |
| $largestSubtitleFile = $subtitleFiles | Sort-Object -Property Length -Descending | Select-Object -First 1 | |
| if ($largestSubtitleFile) { | |
| $newSubtitleFileName = "{0}.{1}.{2}" -f $mediaFileBaseName, $languageCode, $subtitleFormats[0] | |
| $destinationPath = Join-Path -Path $mediaFile.Directory.FullName -ChildPath $newSubtitleFileName | |
| if (-not (Test-Path $destinationPath)) { | |
| Copy-Item -Path $largestSubtitleFile.FullName -Destination $destinationPath -Verbose | |
| } | |
| } | |
| } | |
| } | |
| } | |
| # Continue processing in subdirectories | |
| $childDirectories = Get-ChildItem -Path $directory -Directory | |
| foreach ($childDir in $childDirectories) { | |
| Copy-RenameSubtitles $childDir.FullName | |
| } | |
| } | |
| # Start processing in the specified directory or the current directory if none provided | |
| $currentDirectory = if ($args[0]) { $args[0] } else { Get-Location } | |
| Copy-RenameSubtitles $currentDirectory |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment