firekid2018
firekid2018

Reputation: 145

How to Sync Two Google Drive Folder

I have two folders in my Google Drive account; Folder 1 and Folder 2. I will upload a file in Folder 1 and I want the file to be copied from Folder 1 to Folder 2, but if it already exists in Folder 2 it should not be copied. Here is the script I've got, but when it runs it always copies all the files available in Folder 1 to Folder 2:

function copyfile() {
  var sourceFolderName = "Folder 1";
  var destinationFolderName = "Folder 2";
  var source_folder = DriveApp.getFoldersByName(sourceFolderName).next();
  var files = source_folder.getFiles();
  var dest_folder = DriveApp.getFoldersByName(destinationFolderName).next();
  while (files.hasNext()) {
    var srcFile = files.next();
    var newName = srcFile.getName();
    srcFile.makeCopy(newName, dest_folder);
  }
}

Upvotes: 0

Views: 555

Answers (1)

carlesgg97
carlesgg97

Reputation: 4430

I have modified your code so that:

  1. Gets a list of all the file names in the destination folder.
  2. For each file to copy, it first checks whether that name is in the aforementioned list. In case that it is, it will not create a copy of it.

Modified code

function copyfile() {
  var sourceFolderName = "Folder 1";
  var destinationFolderName = "Folder 2";
  var source_folder = DriveApp.getFoldersByName(sourceFolderName).next();
  var files = source_folder.getFiles();
  var dest_folder = DriveApp.getFoldersByName(destinationFolderName).next();

  var destination_files = [];
  var fileIterator = dest_folder.getFiles()
  while (fileIterator.hasNext())
    destination_files.push(fileIterator.next().getName());

  while (files.hasNext()) {
    var srcFile = files.next();
    var newName = srcFile.getName();
    if (destination_files.indexOf(newName) == -1) {
      srcFile.makeCopy(dest_folder);
    }
  }
}

Upvotes: 1

Related Questions