GAS Folders, Sub Folders and their Files

Google Drive is a wonderful thing, but when it comes to getting at a file with scripts things can get a little quirky. Every file and folder has a unique ID number (28 digits, letters and other marks) which can make it easy to locate it, if you know how. However you can of course have many files, or folders with the same name spread out across your Google Drive, which can create a bit of a problem when trying to find the file or folder. Very often you may have to iterate over “all the folders” in order to find what you want, using names to do this can be problematic.

I find I am routinely needing to grab a list of filenames, file IDs, or file types, and routinely searching the web each time I need to do this, therefore it was about time I tied down the required scripts in one place for reuse. The scripts I have put together will request either a folder name or ID in order to iterate over the files within that folder and return the results to a spreadsheet. The scripts can be used as a base, and edited to suit specific requirements by adding further properties to return, or through the use of if statements to narrow down selected files.

  • You can find the ID of the folder by looking in the url address bar if you have the folder open in Google Drive
  • You can also right click on the folder and then Shareable Link
  • Finding the name should be obvious! – use search in Google Drive to check for folders with the same name. It may be wise to do this occasionally if you use name a lot in your scripts, and to make your folder names unique

In my scripts I have chosen to return the filename, the mime type, the file ID, and to create a download link. I also include a helper script (courtesy of Sandy Good) that presents the mimetype in a more user friendly way. All four folder scripts rely on this. Thanks should also go to Brian P and AD:AM on the google group support forum for their code.

I will add a link to a google sheet which contains all the scripts, just make a copy of it to your own google drive, authorise the scripts and away you go.

Return Files From Folder By ID

 

Return Files From Folder by Name
(beware if you have several folders with the same name, it will return the contents of all of them)

 

Return Files From Folder and its Sub Folders By ID
(note the use of the traversefolders sub routine)

 

Return Files From Folder and its Sub Folders By Name
(note the use of the traversefolders sub routine) also (beware if you have several folders with the same name, it will return the contents of all of them)

Nice Mime Types

You may notice a subtle difference between getting your folder via ID and Name. By Name you have to get all Folders and iterate, whereas (although you can iterate over the Folders if you want) with ID the DriveApp offers you getFolderByID().

Google Sheet

Leave a Reply

Your email address will not be published. Required fields are marked *