Concept
Getting a folder or file
The safest way is by ID — copy it from the URL: drive.google.com/drive/folders/<FOLDER_ID>.
const folder = DriveApp.getFolderById('FOLDER_ID');
const file = DriveApp.getFileById('FILE_ID');
Names are not unique in Drive (two folders can have the same name), so searching by name returns an iterator:
const it = DriveApp.getFoldersByName('Invoices');
while (it.hasNext()) {
const f = it.next();
console.log(f.getName(), f.getId(), f.getUrl());
}
Get-or-create a folder
A helper you'll reuse in many projects:
function getOrCreateFolder(parent, name) {
const it = parent.getFoldersByName(name);
return it.hasNext() ? it.next() : parent.createFolder(name);
}
Example: organise invoices by year and month:
function monthFolder(date) {
const root = DriveApp.getFolderById('INVOICES_ROOT_ID');
const tz = Session.getScriptTimeZone();
const year = getOrCreateFolder(root, Utilities.formatDate(date, tz, 'yyyy'));
return getOrCreateFolder(year, Utilities.formatDate(date, tz, 'MM-MMM')); // e.g. 10-Oct
}
Creating and moving files
// A text/CSV file
const folder = monthFolder(new Date());
const csv = 'Item,Qty\nRing,2\nChain,1';
const file = folder.createFile('stock.csv', csv, MimeType.CSV);
// Move an existing file
DriveApp.getFileById('FILE_ID').moveTo(folder);
// Make a copy in another folder
DriveApp.getFileById('FILE_ID').makeCopy('Copy of report', folder);
Listing files into a sheet
function listFolder() {
const folder = DriveApp.getFolderById('FOLDER_ID');
const files = folder.getFiles();
const out = [['Name', 'Type', 'Size (KB)', 'Last updated', 'Link']];
while (files.hasNext()) {
const f = files.next();
out.push([
f.getName(),
f.getMimeType(),
Math.round(f.getSize() / 1024),
f.getLastUpdated(),
f.getUrl()
]);
}
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Files');
sheet.clearContents();
sheet.getRange(1, 1, out.length, out[0].length).setValues(out);
}
Searching with queries
searchFiles uses Drive's search syntax:
const pdfs = DriveApp.searchFiles(
"mimeType = 'application/pdf' and modifiedDate > '2026-10-01T00:00:00' and title contains 'Invoice'"
);
Sharing (carefully)
file.addViewer('customer@example.com'); // share with one person
// file.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW); // anyone with link
Be careful with "anyone with the link" for invoices or customer data — share with specific people where you can.
Key points
- Use IDs when you can; names return iterators because they aren't unique.
getOrCreateFolderprevents duplicate folders.moveTo,makeCopy,createFilecover most organising jobs.