Gleb Zayats
Gleb Zayats

Reputation: 13

Find folder id on google drive by file id

I have a table where a column contains the id of a google spreadsheet file. I need to find the folder where the given table is located and put its id in the adjacent column. I'd like to have a google script that I can run from my spreadsheet to do this kind of search. Unfortunately, I did not find how to get the folder id given the file id.

Upvotes: 0

Views: 1636

Answers (1)

Aaron Dunigan AtLee
Aaron Dunigan AtLee

Reputation: 2072

How to get the (parent) folder id given the file id

Given a Drive file, the method file.getParents() returns a collection (FolderIterator) of parent folders of that file (the method is plural because it used to be possible for a single file to exist in more than one parent folder, though Google has deprecated that model, so it's likely that your file in question only has one parent).

Assuming your file has exactly one parent folder, we can use the FolderIterator class's .next() method to get that folder, so the following snippet will give the folder id, based on the file's fileId:

var folderId = DriveApp.getFileById(fileId).getParents().next().getId()

Upvotes: 1

Related Questions