This is a sample script for retrieving the files of ‘Shared with Me’ in the specific folder using Google Apps Script.
In the current stage, when you transfer the ownership of your file on your Google Drive to another user and/or copy the file “Shared with me” to the specific folder on your Google Drive, the file becomes the shortcut file. Under this situation, when you want to retrieve the files of “Shared with me” in the specific folder, unfortunately, the following search query cannot be used.
'###folderId###' in parents and trashed=false and sharedWithMe
'###folderId###' in parents and trashed=false and not '###your email address###' in owners
It is considered that the reason for this is as follows.
- You are the owner of the shortcut file.
On the other hand, sharedWithMe
and not '###your email address###' in owners
works. But, in this case, the file has no parent folder. Or the parent folder is not in your Google Drive. By this, in order to retrieve the files of “Shared with me” in the specific folder, it is required to use a workaround.
In this post, I would like to introduce a sample script for retrieving the files “Shared with me” in the specific folder.
Sample script
function myFunction() {
const folderId = "###"; // Please set the parent folder ID you want to search.
const email = Session.getActiveUser().getEmail(); // Or, please set email address you want to exclude.
const searchFlies = (folder, res = []) => {
const files = folder.getFiles();
while (files.hasNext()) {
let file = files.next();
file =
file.getMimeType() == MimeType.SHORTCUT
? DriveApp.getFileById(file.getTargetId())
: file;
const owner = file.getOwner() ? file.getOwner().getEmail() : "";
if (owner && owner != email) {
res.push([file.getName(), file.getId(), file.getOwner().getEmail()]);
}
}
const folders = folder.getFolders();
while (folders.hasNext()) searchFlies(folders.next(), res);
return res;
};
const res = searchFlies(DriveApp.getFolderById(folderId));
console.log(res);
}
-
When this script is run, you can obtain the files of “Shared with me”. And, you can see the filename, fileId, and owner of the file in the log.
[ ["filename1", "fileId1", "owner's email 1"], ["filename2", "fileId2", "owner's email 2"], , , , ]
-
In this sample script, all files are searched from all sub-folders under the parent folder.
Reference
- This sample script was answered for this thread in Stackoverflow.