copyFolderRecursive(sourceId, destParentId, opts) copies a Drive folder, every subfolder, and every file into a new (or existing) folder of the same name under destParentId. It returns a log of what was copied, skipped, already there, or unavailable. Pass {skip: '^tmp-'} (a regex or regex string) to leave temp files behind. If the 6-minute Apps Script wall is close, it stops cleanly so a second run can resume.
When to use
- Duplicating a client folder, a template tree, or a project archive
- A copy that is large enough to need a skip list and a resume
- Building a log tab of what actually landed in the destination
How to use this snippet
/**
* Copy a Drive folder and its contents under destParentId.
* Reuses a destination folder with the same name if one already exists,
* and skips files that already exist there, so a second run can resume.
* opts.skip is a RegExp or regex string matched against each name.
* opts.budgetMs defaults to 330000 (5.5 minutes). Returns
* {done, destId, destUrl, results} where each result is
* {action, kind, name, path, sourceId, destId, url, error}.
* action is 'copied', 'exists', 'skipped', or 'unavailable'.
*
* @param {string} sourceId
* @param {string} destParentId
* @param {{skip?: RegExp|string, budgetMs?: number}} [opts]
* @return {{done: boolean, destId: string, destUrl: string, results: Array}}
*/
function copyFolderRecursive(sourceId, destParentId, opts) {
opts = opts || {};
var skipRe = opts.skip == null || opts.skip === ''
? null
: (opts.skip instanceof RegExp ? opts.skip : new RegExp(opts.skip));
var started = Date.now();
var budget = opts.budgetMs == null ? 330000 : Number(opts.budgetMs); // 5.5 min
var results = [];
var timedOut = false;
function hasTime_() {
return (Date.now() - started) < budget;
}
function shouldSkip_(name) {
return !!(skipRe && skipRe.test(name));
}
function first_(it) {
return it.hasNext() ? it.next() : null;
}
var source = DriveApp.getFolderById(sourceId);
var destParent = DriveApp.getFolderById(destParentId);
if (source.getId() === destParent.getId()) {
throw new Error('copyFolderRecursive: destination parent must not be the source folder');
}
var rootName = source.getName();
var destRoot = first_(destParent.getFoldersByName(rootName));
if (destRoot) {
results.push({
action: 'exists',
kind: 'folder',
name: rootName,
path: rootName,
sourceId: source.getId(),
destId: destRoot.getId(),
url: destRoot.getUrl(),
error: ''
});
} else {
destRoot = destParent.createFolder(rootName);
results.push({
action: 'copied',
kind: 'folder',
name: rootName,
path: rootName,
sourceId: source.getId(),
destId: destRoot.getId(),
url: destRoot.getUrl(),
error: ''
});
}
var destIds = {};
destIds[destRoot.getId()] = true;
var seenSource = {};
function walk_(src, dest, path) {
if (timedOut || !hasTime_()) {
timedOut = true;
return;
}
if (seenSource[src.getId()]) return;
seenSource[src.getId()] = true;
var files = src.getFiles();
while (files.hasNext()) {
if (!hasTime_()) {
timedOut = true;
return;
}
var file = files.next();
var name = file.getName();
var filePath = path + '/' + name;
if (shouldSkip_(name)) {
results.push({
action: 'skipped', kind: 'file', name: name, path: filePath,
sourceId: file.getId(), destId: '', url: '', error: ''
});
continue;
}
var existing = first_(dest.getFilesByName(name));
if (existing) {
results.push({
action: 'exists', kind: 'file', name: name, path: filePath,
sourceId: file.getId(), destId: existing.getId(), url: existing.getUrl(), error: ''
});
continue;
}
try {
var copy = file.makeCopy(name, dest);
results.push({
action: 'copied', kind: 'file', name: name, path: filePath,
sourceId: file.getId(), destId: copy.getId(), url: copy.getUrl(), error: ''
});
} catch (e) {
results.push({
action: 'unavailable', kind: 'file', name: name, path: filePath,
sourceId: file.getId(), destId: '', url: '', error: e.message
});
}
}
var folders = src.getFolders();
while (folders.hasNext()) {
if (timedOut || !hasTime_()) {
timedOut = true;
return;
}
var sub = folders.next();
var name = sub.getName();
var subPath = path + '/' + name;
if (destIds[sub.getId()]) {
results.push({
action: 'skipped', kind: 'folder', name: name, path: subPath,
sourceId: sub.getId(), destId: sub.getId(), url: '', error: 'destination folder'
});
continue;
}
if (shouldSkip_(name)) {
results.push({
action: 'skipped', kind: 'folder', name: name, path: subPath,
sourceId: sub.getId(), destId: '', url: '', error: ''
});
continue;
}
var destSub = first_(dest.getFoldersByName(name));
if (destSub) {
results.push({
action: 'exists', kind: 'folder', name: name, path: subPath,
sourceId: sub.getId(), destId: destSub.getId(), url: destSub.getUrl(), error: ''
});
} else {
destSub = dest.createFolder(name);
results.push({
action: 'copied', kind: 'folder', name: name, path: subPath,
sourceId: sub.getId(), destId: destSub.getId(), url: destSub.getUrl(), error: ''
});
}
destIds[destSub.getId()] = true;
walk_(sub, destSub, subPath);
}
}
walk_(source, destRoot, rootName);
return {
done: !timedOut,
destId: destRoot.getId(),
destUrl: destRoot.getUrl(),
results: results
};
}
Example
function backupProjectFolder() {
var report = copyFolderRecursive('SOURCE_FOLDER_ID', 'DEST_PARENT_ID', { skip: '^tmp-|~$' });
var rows = [['Action', 'Kind', 'Path', 'URL', 'Error']].concat(
report.results.map(function (r) {
return [r.action, r.kind, r.path, r.url, r.error];
})
);
var tab = SpreadsheetApp.getActive().getSheetByName('Copy log') ||
SpreadsheetApp.getActive().insertSheet('Copy log');
tab.clear();
tab.getRange(1, 1, rows.length, 5).setValues(rows);
if (!report.done) {
Logger.log('Stopped to stay under the time budget. Run again to resume.');
}
}
Notes
- The destination parent must not be the source folder itself. Prefer a destination that sits outside the source tree; a destination folder encountered while walking is skipped.
makeCopycreates files you own. Sharing on the originals is not copied. Re-share if other people need access to the copies; Share File With Email and List Folder Sharing are the usual follow-on.- A second run reuses the destination folder and files of the same name (
existsin the log) and only copies what is still missing, so a time-budget stop is resumable. Duplicate names under one parent are ambiguous — the first match is used. unavailableusually means DriveApp could not copy that item (some shared-drive files, shortcuts, or items you can see but not copy). The rest of the tree still proceeds.- The default budget is 5.5 minutes, the same idea as Under Time Budget.
Happy Coding!
