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.