I have some files like
The Fast and the Furious Tokyo Drift .avi
The Fast and the Furious 1080p .mkv
I want to rename these filenames in this way
The Fast and the Furious Tokyo Drift.avi
The Fast and the Furious.mkv
But powershell script fails to do this task
I try to run this code
# Specifies the directory containing the files to be renamed
$directory = 'C:\temp\film\test2'
# Ottieni l'elenco dei file nella directory con le estensioni specificate
$files = Get-ChildItem $directory -Include '*.avi', '*.mkv', '*.mp4'
# Initializes a counter for files of the same name
$counter = 1
# Cycle through each file
foreach ($file in $files) {
# Create a search string that locates all occurrences of the words to be deleted,
# regardless of the case
$search = '(?i)\b(ITA|ENG|AC3|BDRip|1080p|X265_ZMachine)\b|\b1080p\b'
# Replace all occurrences of the words to be deleted with an empty string
$newName = $file.Name -replace $search, ''
# Eliminate double spaces
$newName = $newName -replace ' ', ' '
# Remove the spaces at the beginning and end of the file name
# Create the new file name
$newName = "$($newName.TrimEnd())$($file.Extension)"
# Check if the new filename is already in the directory
while (Test-Path -Path "$directory\$newName") {
# If the new file name already exists, add a sequential number to the name
$newName = "$($file.BaseName)_$counter$($file.Extension)"
$counter++
}
# Rename the file to the new name
Rename-Item -Path $file.FullName -NewName $newName
# Reset the counter for files with the same name
$counter = 1
}
In summary, the logic of the code is this
- Specifies the directory containing the files to be renamed.
- Gets the list of files in the directory with the specified extensions using the Get-ChildItem command with the -Include parameter.
- Initializes a counter for files of the same name.
- Loop through each file in the resulting list.
- Create a search string that finds all occurrences of the words to delete, regardless of case.
- Replaces all occurrences of the words to be deleted with an empty string.
- Eliminate double spaces.
- Remove the spaces at the beginning and end of the file name.
- Create the new file name.
- Check if the new filename is already in the directory. If the new name already exists, add a sequential number to the name.
- Rename the file to the new name using the Rename-Item command.
- Reset the counter for files with the same name.