Search code examples
google-apps-scriptcopymovefile

Copy files from one folder to another on Drive with Apps Script


Team members upload content (regardless of file type) into a folder on Drive. I need to copy this content into another folder automatically with a trigger, and be able to move it around from there.

I cannot use a "MoveFile" function as I am not the owner of the original content.

I have already tried to copy files automatically into the destination folder, and this works, using the code below:

function CopyFiles() {
  var srcFldr = DriveApp.getFolderById("***ID***");
  var srcFiles = srcFldr.getFiles();
  var desFldr = DriveApp.getFolderById("***ID***");
  var desFiles = desFldr.getFiles();
  var dfnA = [];
  while (desFiles.hasNext()) {
    var df = desFiles.next();
    dfnA.push(df.getName());
  }
  while (srcFiles.hasNext()) {
    var sf = srcFiles.next();
    if (dfnA.indexOf(sf.getName()) == -1) {
      sf.makeCopy(sf.getName(), desFldr);
    }
  }
}

However, I need to move this copied content into other files throughout the day, yet every time I do, the same file gets copied back into the destination folder above with the new trigger, creating a permanent loop.

Is there a way of either:

  1. moving the files from the original source folder despite not being the owner of those files?
  2. copying contents only once, upon upload or modification?

Or 3) another, better, smarter way of doing this?

Thanks for your help!


Solution

  • I'd suggest the following workflow:

    • For every file that is copied to the destination folder, store the fileId. You could use Properties Service for this.
    • When copying files from one folder to the other, check the fileId has not been stored before.

    Code snippet:

    function CopyFiles() {
      var srcFldr = DriveApp.getFolderById("***ID***");
      var srcFiles = srcFldr.getFiles();
      var desFldr = DriveApp.getFolderById("***ID***");
      var desFiles = desFldr.getFiles();
      var dfnA = [];
      var key = "fileIDs";
      var scriptProperties = PropertiesService.getScriptProperties();
      var property = scriptProperties.getProperty(key); // Retrieve fileIDs property
      // Get array of fileId, or empty array if no file has been copied before:
      var arrayIDs = property ? JSON.parse(property) : []; 
      while (desFiles.hasNext()) {
        var df = desFiles.next();
        dfnA.push(df.getName());
      }
      while (srcFiles.hasNext()) {
        var sf = srcFiles.next();
        // Check not only file name, but also whether fileId has been stored before:
        if (dfnA.indexOf(sf.getName()) == -1 && arrayIDs.indexOf(sf.getId()) == - 1) {
          sf.makeCopy(sf.getName(), desFldr);
          arrayIDs.push(sf.getId()); // Add fileId to array of IDs
        }
      }
      scriptProperties.setProperty(key, JSON.stringify(arrayIDs)); // Store updated array
    }
    

    Reference: