Skip to content

Instantly share code, notes, and snippets.

@bobby-tablez
Created January 5, 2024 03:20
Show Gist options
  • Save bobby-tablez/c77ce69b4974a66a58f65b9a90d96648 to your computer and use it in GitHub Desktop.
Save bobby-tablez/c77ce69b4974a66a58f65b9a90d96648 to your computer and use it in GitHub Desktop.
Batch Rename and Format Media Files
<#
Batch rename "downloaded" media files to make the file names more appealing.
Supply a directory to be scanned recursively: "rename-media.ps1 C:\path\to\media"
IE: "the.sum.of.all.fears.2002.1080p.BLAH.Text.Atmos.COOLPEOPLE.mkv" to "The Sum Of All Fears (2002).mkv"
#>
Param (
[string]$Path
)
Function Rename-Files {
Param (
[string]$path
)
# Get all files in the directory recursively.
$files = Get-ChildItem -Path $path -Recurse -File
Foreach ($file in $files) {
$name = $file.BaseName
$extension = $file.Extension
# Replace '.' with spaces except for the extension separator.
$name = $name -replace '\.', ' '
# Detect a year between 1950 and 2024 and format the filename accordingly
If ($name -match '(.*)(\b(19[5-9][0-9]|20[0-1][0-9]|202[0-4])\b).*') {
$preDateText = $matches[1]
$year = $matches[2]
# Capitalize the first letters of each word
$preDateText = ($preDateText -split ' ' | ForEach-Object {
if ($_.Length -gt 0) {
$firstChar = $_.Substring(0,1).ToUpper()
$rest = if ($_.Length -gt 1) { $_.Substring(1).ToLower() } else { "" }
$firstChar + $rest
}
}) -join ' '
# Check if the year is already wrapped in parenthesis, if not, add them
If ($year -match '^\(.*\)$') {
$name = $preDateText + $year
} Else {
$name = $preDateText + " (" + $year + ")"
}
}
# Construct the new filename
$newName = $name + $extension
# Rename the file
Rename-Item -Path $file.FullName -NewName $newName
}
}
Rename-Files -path $Path
Write-Host "Renaming complete."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment