Skip to content

Instantly share code, notes, and snippets.

@abdelkrimdev
Created May 10, 2025 14:41
Show Gist options
  • Select an option

  • Save abdelkrimdev/0b0ad35be204486ca7a7e53e5e280c23 to your computer and use it in GitHub Desktop.

Select an option

Save abdelkrimdev/0b0ad35be204486ca7a7e53e5e280c23 to your computer and use it in GitHub Desktop.
A PowerShell script using MKVToolNix (CLI) to batch rename subtitles in your Matroska Video files (MKV)
$folderPath = "."
$newName = ""
# Ensure mkvmerge is available
if (-not (Get-Command mkvmerge -ErrorAction SilentlyContinue)) {
Write-Error "mkvmerge is not installed or not found in PATH."
return
}
function Set-SubtitleName {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]$InputFile,
[Parameter(Mandatory = $true)]
[string]$SubtitleTrackID,
[Parameter(Mandatory = $true)]
[string]$SubtitleName
)
$args = @(
'-o', "./renamed/`"${InputFile}`"",
'--track-name', "${SubtitleTrackID}:`"${SubtitleName}`"",
"`"${InputFile}`""
)
Write-Host "Running: mkvmerge $($args -join ' ')"
& mkvmerge @args
if ($LASTEXITCODE -eq 0) {
Write-Host "✅ Subtitle track name updated: $OutputFile"
} else {
Write-Error "❌ mkvmerge failed to update subtitle name."
}
}
function Get-SubtitleTrackIDs {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]$InputFile
)
$info = & mkvmerge -i "$InputFile"
if ($LASTEXITCODE -ne 0) {
Write-Error "Failed to get track info from '$InputFile'."
return
}
# Extract subtitle track IDs
$tracks = $info | Select-String -Pattern 'Track ID (\d+): subtitles' |
ForEach-Object {
[PSCustomObject]@{
ID = [int]($_.Matches[0].Groups[1].Value)
Description = $_.Line.Trim()
}
}
if ($tracks.Count -eq 0) {
Write-Warning "No subtitle tracks found in '$InputFile'."
}
return $tracks
}
function Set-SubtitleNameInFolder {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]$FolderPath,
[Parameter(Mandatory = $true)]
[string]$SubtitleName
)
if (-not (Test-Path $FolderPath)) {
Write-Error "The path '$FolderPath' does not exist."
return
}
$files = Get-ChildItem -Path $FolderPath -Filter *.mkv -File
if ($files.Count -eq 0) {
Write-Warning "No .mkv files found in '$FolderPath'."
return
}
foreach ($file in $files) {
Write-Host "`nProcessing: $($file.Name)"
$SubtitleTrack = Get-SubtitleTrackIDs -InputFile $file.FullName
Set-SubtitleName -InputFile $file.Name `
-SubtitleTrackID $SubtitleTrack.ID `
-SubtitleName $SubtitleName `
}
}
Set-SubtitleNameInFolder -FolderPath $folderPath -SubtitleName $newName
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment