One folder name isn't enough when exports land under Exports/2026/09 or Clients/Acme/Incoming. Walk a slash-separated path from a parent folder, creating any missing segment as you go. Builds on the same idea as getOrCreateFolder, but for nested paths.
What you'll need
- A parent
Folder(prefer an ID in production) - A path string using
/(or\) separators — empty segments are ignored
How to use this snippet
function getOrCreateFolderPath(parent, path) {
if (!parent) {
throw new Error('getOrCreateFolderPath: parent folder required');
}
var parts = String(path || '')
.split(/[/\\]+/)
.map(function (p) { return p.trim(); })
.filter(Boolean);
var folder = parent;
for (var i = 0; i < parts.length; i++) {
var name = parts[i];
var kids = folder.getFoldersByName(name);
folder = kids.hasNext() ? kids.next() : folder.createFolder(name);
}
return folder;
}
Example
function exportCsvThisMonth() {
var root = DriveApp.getFolderById('YOUR_PARENT_FOLDER_ID');
var tz = Session.getScriptTimeZone();
var year = Utilities.formatDate(new Date(), tz, 'yyyy');
var month = Utilities.formatDate(new Date(), tz, 'MM');
var dest = getOrCreateFolderPath(root, 'Exports/' + year + '/' + month);
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Report');
var csv = valuesToCsv(sheet.getDataRange().getValues()); // your helper
dest.createFile('report.csv', csv, MimeType.CSV);
return dest.getUrl();
}
Tips:
- If sibling folders share a name,
getFoldersByNamereturns the first — keep path segments unique under each parent. - Passing an empty path returns the parent unchanged.
- Prefer a stable parent folder ID so a rename of "Exports" in the UI doesn't break the script.
Happy Coding!
