I have a script that will scan the source and target folders on Google Drive but it takes a long time to run (400 seconds or more).
Below is the code used to scan the source one file and one folder at a time and then look in the target drive to see if the file or folder exists. If it does not, then the file is copied or a folder is created.
I'd like a script to much more quickly scan a source drive and to scan a target drive and to copy any missing files from source to target.
function copyFilesRecursively() {
var sourceFolderId = '###source UID###';
var destinationFolderId = '###target UID###';
var sourceFolder = DriveApp.getFolderById(sourceFolderId);
var destinationFolder = DriveApp.getFolderById(destinationFolderId);
copyFolderContents(sourceFolder, destinationFolder);
}
function copyFolderContents(source, destination) {
var folders = source.getFolders();
while (folders.hasNext()) {
var subFolder = folders.next();
var existingFolder = getFolderByName(destination, subFolder.getName());
var newFolder;
if (existingFolder) {
newFolder = existingFolder;
} else {
newFolder = destination.createFolder(subFolder.getName());
}
copyFolderContents(subFolder, newFolder);
}
var files = source.getFiles();
while (files.hasNext()) {
var file = files.next();
copyFile(file, destination);
}
}
function copyFile(sourceFile, destinationFolder) {
// Check the MIME type of the source file
var sourceMimeType = sourceFile.getMimeType();
// Check if the source file is a Google Apps Script - if it is, then do not copy it
if (!(sourceMimeType === 'application/vnd.google-apps.script')) {
// Source file is not a Google Apps Script, proceed with copying
// Check if a file with the same name already exists in the destination folder
var destinationFiles = destinationFolder.getFilesByName(sourceFile.getName());
if (! destinationFiles.hasNext()) {
// File doesn't exist in the destination, create a new one
var newFile = destinationFolder.createFile(sourceFile.getBlob());
newFile.setName(sourceFile.getName());
}
}
}
function getFolderByName(parentFolder, folderName) {
var folders = parentFolder.getFoldersByName(folderName);
return folders.hasNext() ? folders.next() : null;
}
Any suggestion on how to only copy missing files MORE quickly?