1

I am trying to list all the files I have in a shared drive in a spreadsheet with their name and the URL link.

I came across the following Google script

function findFilesInfo() {

  const folderId = '1vNaHwTQ2WObU9Hil5GMqXdiokYp5wfDH'
  const folder = DriveApp.getFolderById(folderId)
  const files = folder.getFiles()
  const source = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = source.getSheetByName('Sheet2');
  const data = [];
  
  while (files.hasNext()) {
      const childFile = files.next();
      var info = [ 
        childFile.getName(), 
        childFile.getUrl(),
        childFile.getLastUpdated(),  
      ];
    
    data.push(info);
  }
  sheet.getRange(2,1,data.length,data[0].length).setValues(data);
}

From the following question here

I tried to implement it and it's working for my own personal drive, but when I change the ID to a shared drive, it keeps giving me the following error:

TypeError: Cannot read property 'length' of undefined (line 20, file "get name")

I tried removing the data.length or set a specific number for the getRange function, it all gives me the same error.

Am I doing anything wrong here?

Rubén
  • 34,714
  • 9
  • 70
  • 166
Mike
  • 11
  • 2

1 Answers1

0

Replace

sheet.getRange(2,1,data.length,data[0].length).setValues(data);

by

if(data.length > 0) sheet.getRange(2,1,data.length,data[0].length).setValues(data);

The above because the error message will occur when the folder hasn't any file.

Related Q/A about working with subfolders

Rubén
  • 34,714
  • 9
  • 70
  • 166
  • Ahh I see! Ok well follow up questions, that folder actually contained sub-folders, so is this why it was returning as empty? If yes, then how can I tweak the script so it keeps opening the sub folders? Thanks! – Mike Mar 07 '21 at 03:30
  • @Mike I added some links that might help you. – Rubén Mar 07 '21 at 04:58