Skip to content Skip to sidebar Skip to footer

I Need To List All The Files In Subfolders Using Google Script

I am trying to make a summary sheet for all files in a folder. This is what I have so far, but I cannot figure out how to list the files in the subfolders of 'folderid'. Any ideas

Solution 1:

Once you get the main folder, you can get the sub-folders. If there are multiple sub-folders, you'll need an inner loop:

I've tested this code and it works:

functiongetAndListFilesInFolder() {
  var arr,f,file,folderName,subFolders,id,mainFolder,name,own,sh,thisSubFolder,url;

  sh = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
  sh.getRange(1, 1, 100, 10).clear({contentsOnly: true})

  id = "Put_Your_FolderID_Here";
  arr = [["CAPITAL PROJECT", "URLs", "OWNER","FOLDER"]];

  mainFolder = DriveApp.getFolderById(id);
  subFolders = mainFolder.getFolders();
  folderName = mainFolder.getName();

  f = mainFolder.getFiles();

  while (f.hasNext()) {
    file = f.next();
    name = file.getName()
    url = file.getUrl()
    own = file.getOwner().getName()

    arr.push([name, url, own, folderName]);
  };

  while (subFolders.hasNext()) {
    thisSubFolder = subFolders.next();
    f = thisSubFolder.getFiles();
    folderName = thisSubFolder.getName();

    while (f.hasNext()) {
      file = f.next();
      name = file.getName()
      url = file.getUrl()
      own = file.getOwner().getName()

      arr.push([name, url, own,folderName]);  
    };
  };

  sh.getRange(1,1, arr.length, arr[0].length).setValues(arr);
  sh.getRange(2,1, arr.length, arr[0].length).sort(1);


  //var second = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2")
  //second.activate()
}

Post a Comment for "I Need To List All The Files In Subfolders Using Google Script"