0

TL;DR: How can I make sure that a copy of a file is stored in the same folder as where the original was created using Google Apps Script?

Long story: I'm working with a Google spreadsheet that is saved in a shared team folder on Google Drive called FileFolder. The team also has another folder structure where certain folders are shared with external parties (ShareFolders A..Z). I cannot be certain that the file will be stored in many other folders as well (e.g. 4thQuarterFolder M).

When I use the menu to make a copy of the file ('File' -> 'Make a copy...') Google suggests the correct folder to use.

However, I want to do this through a script (and other team members should be able to do it via a custom menu). The following script (per documentation) allows me to iterate through the different folders a file is stored in:

  var ss = SpreadsheetApp.getActive();
  var file = DriveApp.getFileById(ss.getId());
  var folders = file.getParents();
  while(folders.hasNext()){
    var folder = folders.next();
    Logger.log(folder.getName());
  }

The thing is, this doesn't tell me which folder to choose as destination in my file.makeCopy(name, destination). I saw here that the 'root' folder is either the last element or at the top of the array (contradicting) but I was unable to see a pattern when testing on my and a colleagues desktop.

a-burge
  • 1,535
  • 1
  • 13
  • 25
  • The destination parameter requires a folder object. So file.makeCopy(name, DriveApp.getFolderById("folder ID")) would copy the file to the folder specified by ID. – James D Jul 30 '18 at 07:22
  • By "root folder", do you mean the first folder where the file was created? – ScottMcC Jul 30 '18 at 09:32
  • Yes @ScottMcC, that's exactly what I mean. It's birthplace if you wish. – a-burge Jul 30 '18 at 12:33
  • @JamesD, please read the question. My problem is that I don't know which folder object to choose. – a-burge Jul 30 '18 at 12:34
  • 1
    Seems like you need to inspect metadata to decide. You can get a lot of metadata using the Drive REST API instead of DriveApp, but it's harder to do. For starters you can ignore any folders created after the file, or any folders not shared with the creating user – tehhowch Jul 30 '18 at 13:38
  • Well that sucks @tehhowch, would have expected it to be a bit more obvious. But thanks for the directions. – a-burge Jul 30 '18 at 13:43
  • 1
    You can also try [Advanced Google services](https://developers.google.com/apps-script/guides/services/advanced), this will enable you to use web API like Drive in Apps Script. @tehhowch is right, this would be hard. A `parentID` should not be treated as a path as stated in this [SO post](https://stackoverflow.com/a/29880141/5995040), it is just an array list of `parentID` if a file has multiple parentID. – Mr.Rebot Jul 31 '18 at 23:20

0 Answers0