Search code examples
powershellcsvbatch-rename

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


I need to batch rename 2,000+ folders and then rename the pictures inside these folders with the folder new name + the product name + a sequential number + the ".jpg" extension, all of this based on a CSV file that I've created that look like this:

folder_old_name,folder_new_name,folder_path,product_name
102597,WK240,C:\Users\Elvis\Desktop\Products\WK240,CASIO_DIGITAL_PIANO

Here is an example of a current folder and its content:

102597
CASIODIGITALPIANOFRONT.jpg
CASIODIGITALPIANOSIDE.jpg
CASIODIGITALPIANOWITHBOX.jpg

After the process it must look like this:

WK240
WK240_CASIO_DIGITAL_PIANO_1.jpg
WK240_CASIO_DIGITAL_PIANO_2.jpg
WK240_CASIO_DIGITAL_PIANO_3.jpg

I've managed to rename all folders with the help of this below code but I have no idea on how to include an instruction to rename the files in the way I've described.

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

I would appreciate it if someone could help me to do this all at once.


Solution

  • basic steps are:

    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
    

    I havn't test this code, but this is basically what it could look like.

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