Google Apps Script that selects all files in a specified Google Drive folder and lists their details

Steps to Implement:

  1. Open the Apps Script Editor:
    • Go to your Google Sheet.
    • Click Extensions > Apps Script.
  2. Copy and paste the script below.
  3. Replace the folder ID with your target folder ID.
  4. Run the script.

Code:

function listFilesInFolder() {
const folderId = "YOUR_FOLDER_ID"; // Replace with your Folder ID
const folder = DriveApp.getFolderById(folderId);
const files = folder.getFiles();
const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();

// Clear existing content in the sheet
sheet.clear();

// Add headers
sheet.appendRow(["File Name", "File ID", "File Path"]);

while (files.hasNext()) {
const file = files.next();
const fileName = file.getName();
const fileId = file.getId();
const filePath = getFullPath(file);

// Append file details to the sheet
sheet.appendRow([fileName, fileId, filePath]);
}
}

/**
* Helper function to get the full path of a file
* @param {DriveApp.File} file - The file object
* @returns {string} - Full path of the file
*/
function getFullPath(file) {
let currentFolder = file.getParents().next(); // Get the parent folder
let path = currentFolder.getName();

while (currentFolder.getParents().hasNext()) {
currentFolder = currentFolder.getParents().next();
path = currentFolder.getName() + " > " + path; // Construct the path
}

return path;
}

Instructions:

  1. Replace "YOUR_FOLDER_ID" with the ID of the Google Drive folder whose files you want to list.
    • Find your folder ID from the folder’s URL. For example:rubyCopy codehttps://drive.google.com/drive/folders/FOLDER_ID
  2. Open the Google Sheet where you want to save the file details.
  3. Run the listFilesInFolder function from the Apps Script Editor.
  4. Authorize the script when prompted.

Output:

  • The script clears any existing data in the active sheet.
  • Adds headers: File Name, File ID, and File Path.
  • Lists all files in the folder with their details.

Example:

File NameFile IDFile Path
Example.docx1A2B3C4D5E6F7G8H9I0JMy Drive > Folder Name
Image.png9I8H7G6F5E4D3C2B1AMy Drive > Folder Name

This script provides a comprehensive list of files in a folder, including their paths, IDs, and titles, directly within your Google Sheet. Let me know if you need any modifications!