I have built an apps script add-on that looks at a column in Google sheets with Doc IDs in google drive and determines the folder path of the file using those doc IDs.
The only issue is it does not give me the root folder. So if a file is located in the following folder path:
"root folder / sub-folder / sub-folder / sub-folder"
I get the following path with my code:
"Drive / sub-folder / sub-folder / sub-folder"
It says "Drive" for every file located in a shared drive and not the name of the actual root folder.
Here is the code i have currently:
function getFolderPath(id) {
var sheet = SpreadsheetApp.getActiveSheet();
var dataRange = sheet.getDataRange();
var values = dataRange.getValues();
var docIdCol = 3; // assuming doc_id is in column C
var folderPathCol = docIdCol + 1; // insert new column beside column C
var folderPath;
// insert new column beside column C
sheet.insertColumnBefore(folderPathCol);
// set column header
sheet.getRange(1, folderPathCol).setValue("Folder Path");
// iterate through each row and get folder path for each file
for (var i = 1; i < values.length; i++) {
var docId = values[i][docIdCol - 1];
try {
var file = DriveApp.getFileById(docId);
var folders = file.getParents();
while (folders.hasNext()) {
var folder = folders.next();
folderPath = folder.getName() + "/" + folderPath;
folders = folder.getParents();
console.log(folders)
}
sheet.getRange(i + 1, folderPathCol).setValue(folderPath);
folderPath = "";
} catch (e) {
sheet.getRange(i + 1, folderPathCol).setValue("My Drive");
}
}
}
2
Answers
Try this one also:
From your following reply,
From your reply, I noticed that I have misread your question. I noticed that you have been using the shared Drive. In this case, it seems that in the current stage, the drive name and the drive ID cannot be directly retrieved with the Drive service (DriveApp).
I guessed that the reason for your current issue is due to that in the current stage, the drive name is required to be retrieved with the method of "Method: drives.get" of Drive API. When this is reflected in your showing script, how about the following modification?
Modified script:
Before you test this script, please enable Drive API at Advanced Google services.
References: