DEV Community

Wriju's Blog
Wriju's Blog

Posted on

Recursive File List from Google Drive

Script Code

function onOpen() {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var searchMenuEntries = [{
        name: "Create a File List from Folder",
        functionName: "start"
    }];
    ss.addMenu("File List", searchMenuEntries);
}


function start() {
    var sheet = SpreadsheetApp.getActiveSheet();
    sheet.clear();
  //Comment below enable it if you need one sheet
    sheet.appendRow(["Name", "Folder", "Type", "Date", "Size", "URL" ]);

    var folderName = Browser.inputBox("Enter Folder Name (this will destroy the current spreadsheet):");
    //var folderName = "Safety Subdomain Assets";

    var folder = DriveApp.getFoldersByName(folderName);

    if (folder.hasNext()) {
        processFolder(folder);
    } else {
        Browser.msgBox('Folder not found!');
    }


    function processFolder(folder) {
        while (folder.hasNext()) {
            var f = folder.next();
            var contents = f.getFiles();
            addFilesToSheet(contents, f);
            var subFolder = f.getFolders();
            processFolder(subFolder);
        }
    }

    function addFilesToSheet(files, folder) {      
        var data;
        var folderName = folder.getName();
      //Delete this two lines below if you need one Sheet
//      sheet.appendRow(["Folder: " + folder]);
//      sheet.appendRow(["Name", "Folder", "Type", "Date", "Size", "URL" ]);
        while (files.hasNext()) {
            var file = files.next();
            Logger.log(file.getName());

            sheet.appendRow([
      file.getName(),
      folderName,
      file.getMimeType(),
      file.getDateCreated(),
      file.getSize()/1024,
      file.getUrl()  

    ]);
        }
    }

}
Enter fullscreen mode Exit fullscreen mode

Discussion (1)

Collapse
tangawk profile image
tangawk

I've tried a few scripts to do this, and the code above is by far the best google drive script for recursive listing of folder contents I've seen. Cool to be able to enter a custom folder name (amazingly many others need it entering directly in the code). And to see it completing in real time. Many thanks for posting !