This Google Apps Script copies the entire folder structure and its contents from the specified source folder to the specified destination folder. It uses recursion to handle subfolders within the source folder, ensuring that the entire folder hierarchy is replicated in the destination folder.
How to run the script
- Create a new Google Apps Script via your Google Drive or by going to script.google.com/create.
- Copy the script from below and paste it into the editor, replacing any existing code.
- Give your project a name by clicking on “Untitled project” at the
top-left and entering a name for your script (e.g., “Copy Drive Folder”). Click the floppy disk icon to save your script. - Replace the placeholder values
YOUR_SOURCE_FOLDER_ID_HERE
andYOUR_DESTINATION_FOLDER_ID_HERE
in the script with the actual Google Drive folder IDs that you want to use as the source and destination folders. - Click the triangular “Run” button to execute the selected “copyFolderRecursively” function.
- After the script completes, you can check the destination folder in your Google Drive to ensure that the folder structure and files have been copied as expected.
Warning: Google Apps Script imposes runtime restrictions. For Gmail accounts, the maximum execution time for a single script run is capped at 6 minutes, while for Workspace accounts, it extends to 30 minutes. If a script takes longer than this, it will be terminated.
Script
function copyFolderRecursively() {
// Source folder ID (the folder you want to copy)
var sourceFolderId = "YOUR_SOURCE_FOLDER_ID_HERE";
// Destination folder ID (the folder where you want to copy to)
var destinationFolderId = "YOUR_DESTINATION_FOLDER_ID_HERE";
// Get the source folder
var sourceFolder = DriveApp.getFolderById(sourceFolderId);
// Create a new folder in the destination folder with the same name as the source folder
var destinationFolder = DriveApp.getFolderById(destinationFolderId).createFolder(sourceFolder.getName());
// Copy the contents of the source folder to the destination folder recursively
copyFolderContents(sourceFolder, destinationFolder);
}
function copyFolderContents(sourceFolder, destinationFolder) {
var files = sourceFolder.getFiles();
while (files.hasNext()) {
var file = files.next();
file.makeCopy(file.getName(), destinationFolder);
}
var subfolders = sourceFolder.getFolders();
while (subfolders.hasNext()) {
var subfolder = subfolders.next();
var newSubfolder = destinationFolder.createFolder(subfolder.getName());
copyFolderContents(subfolder, newSubfolder);
}
}
// Run the copyFolderRecursively function to start the copying process
function runCopyFolderRecursively() {
copyFolderRecursively();
}
Be First to Comment