Created
May 24, 2024 15:48
-
-
Save JayGoldberg/b5dc4da21f73f16be0abdedb73713065 to your computer and use it in GitHub Desktop.
Recursive enumeration of all files in a Google Drive folder to text file on Drive
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getAllFiles(folderId) { | |
const accumulated = []; | |
const folder = DriveApp.getFolderById(folderId); | |
// Function to copy a file to GCS, handling file or folder path as argument | |
function traverseOrReturnItem(item, currentPath) { | |
const itemName = item.getName(); // Handles file or folder names | |
const thisPath = `${currentPath}${currentPath ? "/" : ""}${itemName}`; // Construct GCS object key | |
// if (typeof item === 'object' && item.getMimeType() ? false : true && DriveApp.getFolderById(item.getId()) ? true : false) { // If it's a folder, process contents recursively | |
if (Object.hasOwn(item, "getFiles")) { | |
// Logger.log("thiis is a folder") | |
const directoryFiles = item.getFiles(); | |
while (directoryFiles.hasNext()) { | |
traverseOrReturnItem(directoryFiles.next(), thisPath); // Recursive call | |
} | |
const subFolders = item.getFolders(); | |
while (subFolders.hasNext()) { | |
traverseOrReturnItem(subFolders.next(), thisPath); // Recursive call | |
} | |
} else if (Object.hasOwn(item, "getBlob")) { | |
// Logger.log("this is a file") | |
//Logger.log(`${thisPath}`) | |
accumulated.push([item.getId(), thisPath]); | |
} | |
} | |
traverseOrReturnItem(folder, ""); // Start with the main folder | |
return (accumulated); | |
} | |
function writeFileSummaryToDrive(folderId) { | |
const allFiles = getAllFiles(folderId); | |
const allFilesContent = allFiles.map(file => `${file[0]}: ${file[1]}`).join('\n'); | |
// Search for an existing file named 'allfiles.txt' | |
const files = DriveApp.getFilesByName('allfiles.txt'); | |
let file; | |
if (files.hasNext()) { | |
file = files.next(); | |
file.setContent(allFilesContent); | |
} else { | |
file = DriveApp.createFile('allFilesSummary.txt', allFilesContent); | |
} | |
Logger.log('File written: ' + file.getUrl()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment