I have some files as
young Devils.mkv
hellraiser.avi
Hellraiser 2.mkv
I have in same folder a text file called movielist.txt
that contains this text
Ghost (1990)
Young Devils (1999)
Hellraiser (1987)
Hellraiser 2 (1988)
They Live (1988)
I try to rename my files in this way
Young Devils (1999).mkv
Hellraiser (1987).avi
Hellraiser 2 (1988).mkv
One idea is this, but I don't understand how the comparison with the names in the text file should happen
$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 |
CodePudding user response:
All you would really need is to loop through your names in your .txt file, and match them with the names of the files you're looking to rename.
$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
}
}
}
We do this here using the -match
operator seeing as you can match the BaseName property, to the file name in your .txt file.
Remove the -WhatIf
switch when you've determined those are the results you are after.