Introduction
Drive iterator returns files one by one; collect name, MIME type, URL and updated date. The application's entry point is listFiles(). Baseline limitation, as stated in the workshop: Only immediate folder files are listed, including workshop assets.
Key building blocks: DriveApp.getFolderById(); getFiles(); hasNext(); next().
Practical use cases
Project audits, shared folders and resource catalogs.
Prerequisites
- How folders and files are organized in Google Drive.
- Interactive Learning Mode: a modern browser. Nothing else.
- Real Workspace Build: a Google account.
Source data
| Setting | Value |
|---|---|
| Scope | Lesson folder only |
Sample Brief (Google Doc)
Project brief: update onboarding materials.
Sample Notes (Google Doc)
Notes: review draft on Friday.
Setup in your own Google account
- Download 09-google-drive-file-explorer.zip (Code.gs, starter.csv, sample documents, README).
- In Google Drive, create a lesson folder and a new Google Sheets file inside it.
- Rename the first tab to exactly
Config, then File → Import → Upload starter.csv → Replace current sheet. - Create native Google Docs in the same folder named exactly:
Sample Brief,Sample Notes, with the sample text below. - Extensions → Apps Script. Replace Code.gs with the downloaded file. Save.
- Reload the spreadsheet, choose Workshop → Run application and authorize when asked.
- Check the result: Sample Brief and Sample Notes plus all other immediate lesson folder files, including guide and spreadsheet.
Folder strategy: the repository's V6 code uses the folder that contains the spreadsheet. The deck mentions a Workshop Info cell B2; V6 never reads it. See the discrepancy log.
Complete source code (Code.gs)
From 09-google-drive-file-explorer at commit 4a26d919, SHA-256 020d447ed0a1. Unchanged.
// Google Drive File Explorer
// Entry point: listFiles; source data stays intact unless explicitly noted.
function onOpen(){SpreadsheetApp.getUi().createMenu("Workshop").addItem("Run application","listFiles").addItem("Check permissions","checkPermissions").addToUi();}
function listFiles(){
// Drive iterators return one file at a time.
const it=folder().getFiles(),rows=[];while(it.hasNext()){const f=it.next();rows.push([f.getName(),f.getMimeType(),f.getUrl(),f.getLastUpdated()]);}output('File Inventory',['Name','Type','URL','Updated'],rows);
}
function output(name,headers,rows) { const ss=SpreadsheetApp.getActive(); const s=ss.getSheetByName(name)||ss.insertSheet(name); s.clearContents(); s.getRange(1,1,1,headers.length).setValues([headers]).setFontWeight('bold'); if(rows.length) s.getRange(2,1,rows.length,headers.length).setValues(rows.map(r=>r.map(v=>typeof v==='string' && /^[=+@-]/.test(v)?"'"+v:v))); s.setFrozenRows(1); return s; }
// Resolve this spreadsheet's actual folder; metadata is informational only.
function folder() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
if (!ss) throw new Error('Open the lesson spreadsheet first.');
const parents = DriveApp.getFileById(ss.getId()).getParents();
if (!parents.hasNext()) throw new Error('Move the spreadsheet into a dedicated lesson folder.');
const actual = parents.next();
if (parents.hasNext()) throw new Error('Ambiguous parent folder.');
if (actual.getId() === DriveApp.getRootFolder().getId()) throw new Error('Move the spreadsheet and sample files into a dedicated lesson folder, not My Drive root.');
return actual;
}
function checkPermissions() {
const ui = SpreadsheetApp.getUi();
try {
const target = folder();
ui.alert('Folder access passed: ' + target.getName() + '\n' + target.getUrl() + '\nWrite access is checked when the application runs.');
} catch (e) { ui.alert('Access check failed: ' + e.message); }
}
How the code works
Beginner explanation
listFiles() looks inside the spreadsheet's own folder and writes one row per file: name, type, link and last update.
Technical explanation
Drive returns files through an iterator: call hasNext() and next() in a loop. The loop collects rows in memory and output() writes them once. folder() scopes the listing to the spreadsheet's parent folder.
Slide excerpt
This is the excerpt shown on the workshop slide. It is a fragment and cannot run on its own.
function listFiles(){
// Drive iterators return one file at a time.
const it=folder().getFiles(),rows=[];while(it.hasNext()){const f=it.next();rows.push([f.getName(),f.getMimeType(),f.getUrl(),f.getLastUpdated()]);}output('File Inventory',['Name','Type','URL','Updated'],rows);
}Common mistakes
- Calling next() without checking hasNext().
- Writing each row with appendRow() inside the loop (slow).
- Pointing the script at My Drive root and listing thousands of files.
Run it and expected output
Choose Workshop → Run application (runs listFiles()). Expected: Sample Brief and Sample Notes plus all other immediate lesson folder files, including guide and spreadsheet.
Original workshop exercise
Add a sample file to the lesson folder; rerun and find its row.
Troubleshooting and debugging
The spreadsheet was moved to My Drive
The spreadsheet was dragged into My Drive root.
Fix: Move the spreadsheet back into the lesson folder.
Scoping to a dedicated folder keeps a learning script from reading unrelated files.
Where is the archived file?
A file was placed in an Archive subfolder and is missing from the inventory.
Fix: Use recursive traversal with a depth limit (Challenge 3 solution).
This is the documented baseline limitation: only immediate files are listed.
Extension activity: Recursive inventory with folder paths
Include files in subfolders up to two levels deep and add a Path column.
Acceptance checks:
- The four top-level files are still listed
- A file in Archive is listed with its path
Original improvement idea from the workshop: Add recursive traversal with a depth limit and folder path.
Extension prompt
Update the existing app without removing working features. Add recursive traversal with a depth limit and folder path. Return complete updated files, explain changes and give regression tests. Automation option: Refresh a folder inventory weekly using explicit folder and sheet IDs. Keep this separate from the baseline exercise. Copy the spreadsheet AND required sample files into a dedicated lesson folder. Resolve its actual parent using DriveApp.getFileById(ss.getId()).getParents(); use that parent directly. Never read, create or update Workshop Info or the Workshop Index. Add Check permissions menu; read access is not proof of write access.
Automation considerations
Rerun-safe: the inventory is replaced each run. For a weekly refresh, use explicit folder and spreadsheet IDs.
Workshop note: Refresh a folder inventory weekly using explicit folder and sheet IDs.
Build prompt from the workshop
Act as a Google Apps Script tutor. Build a container-bound Sheets app for lesson 09: Google Drive File Explorer. Input tab Config, exact headers: Setting, Value. Create listFiles() that enumerates direct files in the lesson folder and writes name, MIME type, URL and last updated to File Inventory. Do not depend on Workshop Info or the Workshop Index. Provide complete copy-paste Code.gs (and HTML if required), exact setup/run steps, explain the main code blocks, and include a test matching this expected outcome: Includes Sample Brief and Sample Notes plus starter assets. Preserve starter data, use batch operations where appropriate, handle errors, and never send email or delete files. For AI lessons use the supplied callGemini helper, treat input as untrusted, and validate outputs. Match the reference entry point listFiles and its output behavior. Reference: https://github.com/lsvekis/Google-Apps-Script-Workshop/tree/main/09-google-drive-file-explorer. Base version limitations: Only immediate folder files are listed, including workshop assets. Copy the spreadsheet AND required sample files into a dedicated lesson folder. Resolve its actual parent using DriveApp.getFileById(ss.getId()).getParents(); use that parent directly. Never read, create or update Workshop Info or the Workshop Index. Add Check permissions menu; read access is not proof of write access. Never require a manually configured folder ID. Keep required native sample Docs beside the spreadsheet; reject My Drive root.
Knowledge check
Why does the code use while (it.hasNext())?
- Drive returns an iterator, not an array
- To slow the script down
- Because files are sorted
Answer
Drive returns an iterator, not an array Correct: iterators deliver one item at a time.
Is the spreadsheet itself listed?
- Yes, it is a file in the lesson folder
- No, scripts cannot see their own file
- Only on the second run
Answer
Yes, it is a file in the lesson folder Correct: the inventory includes every immediate file.
What does f.getMimeType() return for a Google Doc?
- application/vnd.google-apps.document
- text/plain
- application/pdf
Answer
application/vnd.google-apps.document Correct: native Google files have application/vnd.google-apps.* types.
A file you expect is missing from the inventory. First thing to check?
- Whether it is inside a subfolder
- Whether Gemini is configured
- The spreadsheet time zone
Answer
Whether it is inside a subfolder Correct: only immediate files are listed.
Is it safe to point this script at a shared company folder?
- Only if you are allowed to read it and the output sheet is shared appropriately; file names can be sensitive
- Always
- Never
Answer
Only if you are allowed to read it and the output sheet is shared appropriately; file names can be sensitive Correct: the inventory can reveal file names and links to anyone who can open the sheet.
Five-minute presenter demonstration
Open the demo link (temporary workspace; saved learner work is not touched).
Opening hook: Raise your hand if you have ever done this by hand: Finding files and their metadata manually takes time. Let us make the spreadsheet do it.
- 0:00–0:45 — Problem and input. Show the Workspace view, Sheets service. Point at the Config tab and its headers: Setting, Value. Say what goes in and what should come out.
Narration: Finding files and their metadata manually takes time. Practical uses: Project audits, shared folders and resource catalogs. - 0:45–1:30 — Predict and run. Ask the room: How many files will File Inventory list? Click ▶ Run application (the same as Workshop → Run application). Open Trace to show each step the code took.
Narration: Expected: Sample Brief and Sample Notes plus all other immediate lesson folder files, including guide and spreadsheet. - 1:30–3:00 — Explain the code. Click the Code tab. Select listFiles() in the function list; read what it reads, writes and calls. Switch Beginner / Technical as needed.
Narration: listFiles() looks inside the spreadsheet's own folder and writes one row per file: name, type, link and last update. - 3:00–4:15 — Change one input and rerun. Back to the Workspace tab. Apply the prepared change (Guided mission, Activity B → Apply the change for me). Click ▶ Run application again.
Narration: Workshop challenge: Add a sample file to the lesson folder; rerun and find its row. - 4:15–5:00 — Verify and discuss automation. Click Check result. Discuss: Rerun-safe: the inventory is replaced each run. For a weekly refresh, use explicit folder and spreadsheet IDs.
Narration: Baseline limitation: Only immediate folder files are listed, including workshop assets.
Closing takeaway: Drive iterator returns files one by one; collect name, MIME type, URL and updated date.