r/GoogleAppsScript • u/aDucklingFromGomsk • Nov 13 '21
Question G Apps Script iterating thru folder structure and copying files
Hi all,
Using G Apps Script, how hard do you guys think it would be to iterate through a Google Drive folder that has several subfolders within, and copy the contents of each subfolder (most files are MS Office and PDFs, some are G Suite) to another folder outside of Google Drive? And, when the file is a G Suite file (Sheets, Docs, Slides), open the file and export it as its equivalent MS Office?
Has anybody done something similar? Any pointers you could recommend? Thank you very much for any guidance
2
u/elvisofdallasDOTcom Nov 13 '21
Iterating is easy - not sure how best to activate the different file types but thinking about this, the easiest process (for me) is to write the whole process in pseudocode then go back and replace with the actual GAS commands
I bet you can knock it out in an afternoon my friend! If you get hung up on a specific step (not sure of the right code) please reply with the action and we will give you the GAS command to make it work
2
u/wadz09 Nov 13 '21
I’m a relative noob to GAS however my suggestion would be to look into WHILE loops. I have been able to iterate through folders and subfolders using a WHILE loop within another WHILE loop. All the file types would have been a Google Sheet but maybe worth looking into for other file types
2
u/HomeBrewDude Nov 13 '21
It's possible, but iterating through every branch of the nested folder structure is a little tricky. Instead, I would recommend using DriveApp.searchFiles() to return a single file iterator and loop through that 'stack' of files. Then there's no need to keep track of the current folder/subfolder and trying to back out of one branch and start the next.
Try writing a function that converts Google to MS format based on the file type. So pass it a fileId and it exports to the appropriate format based on the current MIME type. Then run that in your While loop on the search results.
4
u/_Kaimbe Nov 14 '21
Alternatively, takeout.google.com > select drive and export. It will download everything but much easier to select in file explorer assuming it keeps file structure. It auto exports to docx/pptx/xlxs too