Anton Marks
Anton Marks

Reputation: 13

Why is my Apps Script Trigger Not Working when it works manually?

I am trying to rename file names in a google drive folder as they appear.

It works completely fine when I run this manually but when the automatic trigger is triggered, it fails every time. Manually run it takes between 3 and 5.5 seconds, when triggered it takes between 1 and 1.5 seconds.

I get the error:

TypeError: iA.indexOf is not a function at rename(Code:13:22)

What's wrong?

Here is my code:

function rename(iA = ['20240922', '20240924', '20240930'], 
                oA = ['NNN2024-09-22.mp4', 'NNN2024-09-24.mp4', 'NNN2024-09-30.mp4']) {  

  const SourceFolder = DriveApp.getFolderById("*****************");
  const files = SourceFolder.getFiles();

  while (files.hasNext()) {
    const file = files.next();
    const fileDateMatch = file.getName().match(/(\d{8})/); // Extract date from file name

    if (fileDateMatch) {
      const fileDate = fileDateMatch[1]; // Get the matched date string
      const idx = iA.indexOf(fileDate);

      if (idx !== -1) {
        file.setName(oA[idx]);
        Logger.log(`Renamed file: ${file.getName()} to ${oA[idx]}`); // Log renaming action
      }
    }
  }
}

Thanks in advance for any help you can offer to get this script working.

Set the trigger for every 5 minutes, and it failed every time rather than rename the file names

Upvotes: 1

Views: 77

Answers (1)

TheMaster
TheMaster

Reputation: 50382

Issue:

function rename(iA = ['20240922', '20240924', '20240930'], 
                oA = ['NNN2024-09-22.mp4', 'NNN2024-09-24.mp4', 'NNN2024-09-30.mp4']) {  

When automatically called via trigger, the first argument passed to the called/triggered function is usually the event object e. Therefore,

iA will be a event object e and this event object is not an array and therefore doesn't have indexOf method. So, you get

TypeError: iA.indexOf is not a function at rename(Code:13:22)

Solution:

  • Avoid using the first argument with default parameters, when using triggers
  • or declare iA inside the function

Sample:

function rename(e /*event object*/,iA = ['20240922', '20240924', '20240930'], 
                oA = ['NNN2024-09-22.mp4', 'NNN2024-09-24.mp4', 'NNN2024-09-30.mp4']) {  

Or

function rename(){
  const iA = ['20240922', '20240924', '20240930'];
  const oA = ['NNN2024-09-22.mp4', 'NNN2024-09-24.mp4', 'NNN2024-09-30.mp4']
  const SourceFolder = DriveApp.getFolderById("*****************");
  const files = SourceFolder.getFiles();
//....rest of the code

Related:

When passing variable to function I get 'Invalid argument', but when I hard code it works in Apps Script

Upvotes: 4

Related Questions