通过将文件名与文本文件中的名称进行比较来重命名文件

Rename files by comparing the filenames with the names in a text file

我有一些文件作为

young Devils.mkv
hellraiser.avi
Hellraiser 2.mkv

我在同一文件夹中有一个名为 movielist.txt 的文本文件,其中包含此文本

Ghost (1990)
Young Devils (1999)
Hellraiser (1987)
Hellraiser 2 (1988)
They Live (1988)

我尝试用这种方式重命名我的文件

Young Devils (1999).mkv
Hellraiser (1987).avi
Hellraiser 2 (1988).mkv

一个想法是这样的,但我不明白应该如何与文本文件中的名称进行比较

$rootFolder = 'C:\Test'
$FilesToChange = 'FileNames'
$FileNames = Get-Content "$BasePath\movielist.txt"
# get a list of files
$files = Get-ChildItem -Path $rootFolder -Directory | Sort-Object {$_.Name.Length} -Descending
# find files that match their names
foreach ($FileNames in $files) {
    # use the filenames in movielist.txt as filter, surrounded with wildcard characters (*)
    Get-ChildItem -Path $rootFolder -Filter "*$($FileNames.Name)*" -File |

您真正需要的只是遍历 .txt 文件中的名称,并将它们与您要重命名的文件的名称相匹配。

$rootFolder = "C:\Users\Abraham\Desktop\Test"
$files      = Get-ChildItem -Path $rootFolder -File | Sort-Object { $_.Name.Length } -Descending
$filesNames = Get-Content -Path "$rootFolder\TextFile2.txt"

:loop foreach ($file in $files) 
{
    foreach ($name in $filesNames)
    {
        if ($name -match [regex]::Escape($file.BaseName))
        {
            [pscustomobject]@{
                FileObject = $file.BaseName
                FileName   = $name
            }
            Rename-Item -LiteralPath $file.FullName -NewName "$name$ext" -EA 0 -WhatIf
            continue loop
        }
    } 
}

我们在这里使用 -match 运算符执行此操作,因为您可以将 BaseName 属性 与 .txt 文件中的文件名匹配。


当您确定这些是您想要的结果时,请删除 -WhatIf 开关。