This is a sample of Google Apps Script. This script is for retrieving all files and folders under a folder on Google Drive. All files and folders in the specific folder can be retrieved.
If you want to retrieve file list with all files and folders on Google Drive, please use DriveApp.getRootFolder().getId()
as folderId
.
When there are a lot of files in the folder, it may be over the limitation time to execute script.
Script :
function getFileList(folderId) {
var folderlist = (function(folder, folderSt, results) {
var ar = [];
var folders = folder.getFolders();
while (folders.hasNext()) ar.push(folders.next());
folderSt += folder.getId() + "#_aabbccddee_#";
var array_folderSt = folderSt.split("#_aabbccddee_#");
array_folderSt.pop()
results.push(array_folderSt);
ar.length == 0 && (folderSt = "");
for (var i in ar) arguments.callee(ar[i], folderSt, results);
return results;
})(DriveApp.getFolderById(folderId), "", []);
var localTimeZone = Session.getScriptTimeZone();
var filelist = [];
var temp = {};
for (var i in folderlist) {
var folderid = folderlist[i][folderlist[i].length - 1];
var folder = DriveApp.getFolderById(folderid);
var files = folder.getFiles();
while (files.hasNext()) {
var file = files.next();
temp = {
folder_tree: function(folderlist, i) {
if (i > 0) {
return "/" + [DriveApp.getFolderById(folderlist[i][j]).getName() for (j in folderlist[i])
if (j > 0)].join("/") + "/";
} else {
return "/";
}
}(folderlist, i),
file_id: file.getId(),
file_name: file.getName(),
file_mimetype: file.getMimeType(),
file_created: Utilities.formatDate(file.getDateCreated(), localTimeZone, "yyyy/MM/dd HH:mm:ss"),
file_updated: Utilities.formatDate(file.getLastUpdated(), localTimeZone, "yyyy/MM/dd HH:mm:ss"),
};
filelist.push(temp);
temp = {}
}
}
var sortedlist = filelist.sort(function(e1, e2) {
return (e1.folder_tree > e2.folder_tree ? 1 : -1) });
return sortedlist;
}
Result :
[
{
"folder_tree": "/",
"file_id": "#####",
"file_name": "file name 1",
"file_mimetype": "application/vnd.google-apps.spreadsheet",
"file_created": "2010/01/01 00:00:00",
"file_updated": "2010/01/01 01:00:00"
},
{
"folder_tree": "/folder1/",
"file_id": "#####",
"file_name": "file name 2",
"file_mimetype": "image/png",
"file_created": "2010/01/01 00:00:00",
"file_updated": "2010/01/01 01:00:00"
},
{
"folder_tree": "/folder1/folder2/",
"file_id": "#####",
"file_name": "file name 3",
"file_mimetype": "image/gif",
"file_created": "2010/01/01 00:00:00",
"file_updated": "2010/01/01 01:00:00"
},
,
,
,
]
In this script, Create Folder Tree on Google Drive that I submitted before was used.
Also this script was used at Downloading Files From Google Drive Under No Authorization Using Browser.