如何使用 PowerShell 根据 CSV 文件批量重命名其中的文件夹和文件?

How to batch rename folders and files inside them based on a CSV file with PowerShell?

我需要批量重命名2000+个文件夹,然后将文件夹内的图片重命名为文件夹新名称+产品名称+序号+“.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
    }
}

如果有人可以帮助我一次完成所有这些,我将不胜感激。

这应该会带您完成一部分。无论如何,分两个阶段做事情可能会更好。重命名文件取决于具有新名称的文件夹。

$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. 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++
    }
}