Rename multiple PDFs in google drive using App Script

Viewed 32

I have a batch of PDFs that I need to rename using app script. In my gsheet I have given the "existing name" column and the "new name" column. But when I am running my code, the PDFs are being renamed only by the first letter of the new name instead of complete new name given in my google sheet.

Here is the code I am using:

function rename_pdf(){

var ss = SpreadsheetApp.getActiveSpreadsheet()

var Test =ss.getSheetByName('Sheet15');

  n= 157
for (var i = 2; i < n+1 ; i++ ) {
  
  var Old_Name = Test.getRange(i,3).getValue();
  var New_Name = Test.getRange(i,4).getValue();
  
  const SourceFolder=DriveApp.getFolderById("18YftUIPTfLmrJefh6dd_Pms8Uhh5Dxtg5");
  const Files = SourceFolder.getFiles();
  while(Files.hasNext()) {
    let file=Files.next();
    let idx=Old_Name.indexOf(file.getName());
    if(idx!=-1) {
      file.setName(New_Name[idx])
    }
  }
}
}
1 Answers

Modification points:

  • In your script, New_Name is retrieved by getValue(). But, at New_Name[idx] of file.setName(New_Name[idx]), one of value of the value of New_Name is used. I thought that this is the reason for your issue of the PDFs are being renamed only by the first letter of the new name instead of complete new name given in my google sheet.

  • And, in your script, while(Files.hasNext()) {,,,} is used in a loop. In this case, the process cost of the script becomes high.

  • If you want to search the PDF file, SourceFolder.getFilesByType(MimeType.PDF) might be useful.

When these points are reflected in your script, it becomes as follows.

Modified script:

function rename_pdf() {
  // Retrieve values from Spreadsheet.
  const ss = SpreadsheetApp.getActiveSpreadsheet()
  const sheet = ss.getSheetByName('Sheet15');
  const values = sheet.getRange("C2:D" + sheet.getLastRow()).getValues();

  // Create an object for searching the old filename and new filename.
  const obj = values.reduce((o, [c, d]) => (o[c] = d, o), {});

  // Retrieve file list.
  const SourceFolder = DriveApp.getFolderById("18YftUIPTfLmrJefh6dd_Pms8Uhh5Dxtg5");
  const Files = SourceFolder.getFilesByType(MimeType.PDF); // or SourceFolder.getFiles();
  while (Files.hasNext()) {
    const file = Files.next();
    const filename = file.getName();

    // Rename the filename.
    if (obj[filename]) {
      file.setName(obj[filename]);
    }
  }
}
  • When this script is run, the values of old and new filename are retrieved from the columns "C" and "D". And, the filenames of the files in the folder are renamed using the retrieved values.

References:

Related