Skip to content

Instantly share code, notes, and snippets.

@daweimau
Last active November 2, 2023 09:53
Show Gist options
  • Select an option

  • Save daweimau/a71a2f76eadd06a3172a3850e8dc268e to your computer and use it in GitHub Desktop.

Select an option

Save daweimau/a71a2f76eadd06a3172a3850e8dc268e to your computer and use it in GitHub Desktop.
A Windows powershell script to rename many files (within subfolders)
# I recommend commenting out the `Rename-Item` line and testing, before you actually bulk rename anything
# Recurse from the active directory
Get-ChildItem '.' -Recurse | ForEach-Object {
# Don't rename folders, just files
if ($_ -is [System.IO.FileInfo]) {
# The original filepath (full path)
$oldpath = $_.FullName
# Your own logic here to build the new filename
# Make sure to create a NAME, not a path
$epNum = $_.Name.Substring($_.Name.Length - 7, 3)
$newName = 'Dragon Ball Z Kai ' + 's01e' + $epNum + '.mkv'
# Use `LiteralPath` instead of `Path`, to avoid all kinds of wildcard interpretations etc
Rename-Item -LiteralPath $oldpath -NewName $newName
# Print to terminal
$newName
}
}
# If you want to recurse all but a few directories, you can exclude them with this syntax
Get-ChildItem -Path '.' -Recurse | Where-Object {
if ($_ -is [System.IO.FileInfo]) {
$directoryName = (Get-Item $_.DirectoryName).Name
$directoryName -notin $excludeDirs
} else {
$true # Include directories in the results
}
} |
ForEach-Object {
if ($_ -is [System.IO.FileInfo]) {
$oldpath = $_.FullName
# And here is a way to get just the numbers from the filename
$epNum = [regex]::Replace($_.Name, "[^\d]", "")
$newName = 'Dragon Ball GT ' + 's01e' + $epNum + '.mkv'
Rename-Item -LiteralPath $oldpath -NewName $newName
$newName
}
}
# Another one but more complex because the episodes were numbered 1 -... without season restarts
# Define the starting episode of each season at the top
$seasonMapping = @{
5 = 1
}
# Get all .mkv files in the current directory
$files = Get-ChildItem -Filter *.mkv | Where-Object { $_.PSIsContainer -eq $false }
# Loop through the files and rename them
foreach ($file in $files) {
# Extract the episode number from the original file name
if ($file.Name -match " - (\d+)") {
$fnum = [int]$Matches[1]
# Determine the season based on the mapping
$season = $seasonMapping.GetEnumerator() | Where-Object { $fnum -ge $_.Value } | Sort-Object Value | Select-Object -Last 1
$season = $season.Key
# Calculate the episode number within the season
$episodeInSeason = $fnum - $seasonMapping[$season] + 1
# Format the episode number with leading zeros
$formattedEpisode = "{0:D2}" -f $episodeInSeason
# Create the new name
$newName = "Super Dragon Ball Heroes s0$season" + "e$formattedEpisode.mkv"
# Rename the file
Rename-Item -LiteralPath $file.FullName -NewName $newName
$newName
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment