Я считаю, что в вашем коде есть несколько ошибок, а также код, который вам дал Мануэль.
- Хотя у вас есть список старых и новых имен файлов, вы не используете его в
Get-ChildItem
, но вместо этого попробуйте заменить все найденные файлы. - При использовании
-replace
используется замена регулярного выражения, что означает, что специальный символ .
внутри имени файла рассматривается как Any Character
, а не простоточка. - Вы пытаетесь найти
*.png
файлы, но вы не добавляете -Filter
с командлетом Get-ChildItem
, поэтому теперь он вернет все типы файлов.
В любом случаеУ меня есть другой подход для вас:
Если ваш входной файл C:\1\Srv\MapsName.txt
выглядит примерно так:
picture1.png
ABC_1.png
picture2.png
DEF_1.png
picture3.png
DEF_2.png
Следующий код будет использовать его для создания Hashtable для поиска, чтобы он могдействовать на файлы, упомянутые во входном файле, и оставить все остальные без изменений.
$mapsFile = 'C:\1\Srv\2_MapsName.txt'
$searchPath = 'C:\1\NewMaps'
# Read the input file as an array of strings.
# Every even index contains the file name to search for.
# Every odd index number has the new name for that file.
$lines = Get-Content $mapsFile
# Create a hashtable to store the filename to find
# as Key, and the replacement name as Value
$lookup = @{}
for ($index = 0; $index -lt $lines.Count -1; $index += 2) {
$lookup[$lines[$index]] = $lines[$index + 1]
}
# Next, get a collection of FileInfo objects of *.png files
# If you need to get multiple extensions, remove the -Filter and add -Include '*.png','*.jpg' etc.
$files = Get-ChildItem -Path $searchPath -Filter '*.png' -File -Recurse
foreach ($file in $files) {
# If the file name can be found as Key in the $lookup Hashtable
$find = $file.Name
if ($lookup.ContainsKey($find)) {
# Rename the file with the replacement name in the Value of the lookup table
Write-Host "Renaming '$($file.FullName)' --> $($lookup[$find])"
$file | Rename-Item -NewName $lookup[$find]
}
}
Редактировать
Если входной текстовый файл 'C: \ 1 \ Srv \MapsName.txt 'НЕ содержит имен файлов, включая их расширение, измените заключительный цикл foreach
на следующий:
foreach ($file in $files) {
# If the file name can be found as Key in the $lookup Hashtable
# Look for the file name without extension as it is not given in the 'MapsName.txt' file.
$find = [System.IO.Path]::GetFileNameWithoutExtension($file.Name)
if ($lookup.ContainsKey($find)) {
# Rename the file with the replacement name in the Value of the lookup table
# Make sure to add the file's extension if any.
$newName = $lookup[$find] + $file.Extension
Write-Host "Renaming '$($file.FullName)' --> '$newName'"
$file | Rename-Item -NewName $newName
}
}
Надеюсь, что поможет