powershell不重命名文件并且不识别文件扩展名

6l7fqoea  于 2023-01-17  发布在  Shell
关注(0)|答案(1)|浏览(188)

我有一些文件

The Fast and the Furious Tokyo Drift   .avi
The Fast and the Furious 1080p  .mkv

我想以这种方式重命名这些文件名

The Fast and the Furious Tokyo Drift.avi
The Fast and the Furious.mkv

但powershell脚本无法完成此任务
我试着运行这个代码

# 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
}

总之,代码的逻辑如下
1.指定包含要重命名的文件的目录。
1.使用带有-Include参数的Get-ChildItem命令获取目录中具有指定扩展名的文件列表。
1.初始化同名文件的计数器。
1.循环遍历结果列表中的每个文件。
1.创建一个搜索字符串,查找要删除的单词的所有匹配项,而不考虑大小写。
1.用空字符串替换所有要删除的单词。
1.消除双空格。
1.删除文件名开头和结尾的空格。
1.创建新文件名。
1.检查新文件名是否已在目录中。如果新名称已存在,请在名称中添加序号。
1.使用“重命名项目”命令将文件重命名为新名称。
1.重置同名文件的计数器。

thigvfpy

thigvfpy1#

总结有用的评论:
$files = Get-ChildItem $directory -Include '*.avi', '*.mkv', '*.mp4'
应该是(注意尾随的\*,由于-Include的违反直觉的行为而需要它-参见this answer):

# Only match files of interest located directly in $directory
$files = Get-ChildItem $directory\* -Include *.avi, *.mkv, *.mp4

或者(不需要\*,因为使用了-Recurse):

# Match files of interest located in $directory and any of it subdirs.
$files = Get-ChildItem -Recurse $directory -Include *.avi, *.mkv, *.mp4

$newName = $file.Name -replace $search, ''
应为(.BaseName代替.Name):

$newName = $file.BaseName -replace $search, ''

相关问题