我需要批量重命名2,000个以上的文件夹,然后使用新名称+产品名称+序列号+“ .jpg”扩展名重命名这些文件夹中的图片,所有这些都基于我创建的CSV文件创建的外观如下:
folder_old_name,folder_new_name,folder_path,product_name 102597,WK240,C:\Users\Elvis\Desktop\Products\WK240,CASIO_DIGITAL_PIANO
以下是当前文件夹及其内容的示例:
102597
CASIODIGITALPIANOFRONT.jpg
CASIODIGITALPIANOSIDE.jpg
CASIODIGITALPIANOWITHBOX.jpg
此过程必须如下所示:
WK240
WK240_CASIO_DIGITAL_PIANO_1.jpg
WK240_CASIO_DIGITAL_PIANO_2.jpg
WK240_CASIO_DIGITAL_PIANO_3.jpg
借助下面的代码,我设法重命名了所有文件夹,但是我不知道如何包括按照我所描述的方式来重命名文件的说明。
$invocation = (Get-Variable MyInvocation).Value
$directorypath = Split-Path $invocation.MyCommand.Path
Import-Csv "C:\Users\Elvis\Desktop\batch_rename.csv" | ForEach-Object {
$old = $_.folder_old_name
if (Test-Path ($old)) {
$newPath = $_.folder_new_name
ren $old $newPath
}
}
如果有人可以一次帮助我完成所有任务,我将不胜感激。
答案 0 :(得分:0)
这应该让您参与其中。无论如何,最好分两个阶段进行操作。重命名文件取决于具有新名称的文件夹。
$csv = import-csv input.csv
foreach ($line in $csv) {
$product = $line.product_name
$dir = $line.folder_new_name
$path = $line.folder_path
get-childitem $path\*.jpg |
foreach {$i=1} {
Rename-Item $_ -NewName ($dir + '_' + $product + '_' + $i++) -whatif
}
}
答案 1 :(得分:0)
基本步骤是:
1. import the csv that contains rename instructions
2. loops through the csv
1. rename the folder to its new name
2. get all files in the folder that was just renamed
3. loop through all the files in that folder
1. construct the new name with data from the csv
2. rename the file
我没有测试这段代码,但这基本上就是它的外观。
$csv = import-csv -path "path\to\csv"
# loop through rows in csv
foreach($row in $csv){
# this assumes folder_old_name is in current working directory
# if its not you can use the Join-Path cmdlet to construct the path.
Rename-Item -Path $row.folder_old_name -NewName $row.folder_new_name
# get files and start filename construction
$files = Get-ChildItem -Path $row.folder_new_name
$fileIncrement = 1
$FileBaseName = $row.folder_new_name + '_' + $row.product_name
# loop through files
foreach($file in $files){
# increment filename
$NewFileName = $FileBaseName + '_' + $fileIncrement + $file.Extension
# rename file
Rename-Item -Path $file.FullName -NewName $NewFileName
$fileIncrement++
}
}