Login

Please fill in your details to login.





google drive script for copying files between folders

A Google Apps script comes in handy again to automate a really boring job.
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",
   "second_folderID"
  ];
  dstFolderIds.forEach(makeCopy);
}


function makeCopy(dstFolderId) {
  var srcFolderId = "folderID";
  var srcFolder = DriveApp.getFolderById(srcFolderId);
  var dstFolder = DriveApp.getFolderById(dstFolderId);
  var srcFiles = srcFolder.getFiles();
  while (srcFiles.hasNext()) {
    var file = srcFiles.next();
    var f = file.makeCopy(dstFolder);
    var filename = f.getName().slice(8);
    var dstFileExists = dstFolder.getFilesByName(filename);
    if (dstFileExists.hasNext()) {
      d = dstFileExists.next();
      d.setTrashed(true);
    }
    f.setName(f.getName().slice(8));
    var users = f.getEditors();
    for (user in users) {
      var email = users[user].getEmail();
      if (email != "my_email_Address") {
        f.removeEditor(email);
      }
      f.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW);
    }
  }
}


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: February 26th, 2022
The Computing Café works best in landscape mode.
Rotate your device.
Dismiss Warning