Login

Please fill in your details to login.





google drive script for copying files between folders

Scenario : I have about 15 template files in Google drive that I need to copy to a series of folders
Problem : I have to manually copy each file into the destination folder, rename it to remove 'Copy of ' at the beginning, remove all the editors of the parent folder apart from me (because I want them to be read only templates) and finally change the world permission to view only.
Solution : Google Drive Apps Script 😃

function copy() {
 
  var dstFolderIds = [
   "first_folderID", // Folder ID
   "second_folderID" // Folder ID
  ];
  dstFolderIds.forEach(makeCopy);
}


function makeCopy(dstFolderId) {
  var srcFolderId = "folderID"; // id of the source folder
  var srcFolder = DriveApp.getFolderById(srcFolderId); // Drive folder object for source folder
  var dstFolder = DriveApp.getFolderById(dstFolderId); // Drive folder object for destination folder
  var srcFiles = srcFolder.getFiles(); // Get source folder files as file iterator object
  while (srcFiles.hasNext()) { // keep going whilst there are files in the source folder
    var file = srcFiles.next(); // Get the next file
    var f = file.makeCopy(dstFolder); // Make a copy of the file in the destination folder
    var filename = f.getName().slice(8); // Get filename of new file without 'Copy of ' at the start
    var dstFileExists = dstFolder.getFilesByName(filename); // Get file iterator for existing file
    if (dstFileExists.hasNext()) { // Check whether the file iterator has something in it
      d = dstFileExists.next() // If it does, get the file object
      d.setTrashed(true); // Trash the existing file
    }
    f.setName(f.getName().slice(8)); // Set destination filename - remove 'Copy of '
    var users = f.getEditors(); // Get the editors of the file
    for (user in users) { // Go through each of the editors
      var email = users[user].getEmail(); // Get the editors email address
      if (email != "my_email_Address") { // Check if the editor isn't me :)
        f.removeEditor(email); // Remove the editor
      }
      f.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW); // Set view permission
    }
  }
}


Simply execute the
copy()
script after setting up the list of destination folders and the source folder in
makeCopy()
function. Be aware that there are time limits on code execution so you might find that, depending on how many files you want to copy, you might get a warning about exceeding it.
Last modified: October 5th, 2021
The Computing Café works best in landscape mode.
Rotate your device.
Dismiss Warning