且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

列出Google云端硬盘中的所有文件和文件夹

更新时间:2023-02-14 14:11:41

递归在这种情况下,a>是有益的.下面的代码调用递归方法recurseFolder(),该方法将Folder和Array作为参数.它将文件夹中的所有文件添加到列表中,然后在找到的任何子文件夹中调用自己.

Recursion is beneficial in this case. The code below calls the recursive method recurseFolder() which takes a Folder and Array as a parameter. It adds all the files in the folder to a list, then calls itself on any subfolders it finds.

function test(){
  var root = DriveApp.getRootFolder();
  var list = [];

  var list = recurseFolder(root, list);
  Logger.log(JSON.stringify(list));

  //This is just how I am testing the outputed list. You can do what you need.
  var sheet = SpreadsheetApp.getActiveSheet();
  list.forEach(function (row){
   sheet.appendRow(row); 
  });
}

function recurseFolder(folder, list){
  var files = folder.getFiles();  
  var subfolders = folder.getFolders();

  while (files.hasNext()){ //add all the files to our list first.
    var file = files.next();
    var row = [];
    Logger.log("File: " + folder.getName());
    row.push(folder.getName(),file.getName(),file.getId(),file.getUrl(),file.getSize(),file.getDateCreated(),file.getLastUpdated())
    list.push(row);
  }


  while (subfolders.hasNext()){   //Recurse through child folders.
    subfolder = subfolders.next(); 
    Logger.log("Folder: " + subfolder.getName());
    list = recurseFolder(subfolder, list); //Past the original list in so it stays a 2D Array suitible for inserting into a range.
  }

  return list;
}

我不确定输出的格式是否符合您的预期,因此您可能需要稍微玩一下. 注意:如果在较大的驱动器上运行,它将很容易超时.

I'm not sure if the output is formatted how you intended so you might need to play with it a little. Note: It will easily time out if run on a larger Drive.