Reputation: 35
I want to retrieve a list of files from google drive using GAS. So I want the list of files based on the owner who is empty. For files that we create on the share drive, the owner doesn't exist. If we try to force the owner name, it will get an error.
For example like this:
file.getOwner().getName();
it cannot be retrieved from the file list. I have tried adding a filter based on an empty owner, I would like to say Unknown.
function getfilesUnknown () {
var ss = SpreadsheetApp.getActiveSpreadsheet ();
var st = ss.getActiveSheet ();
var files = DriveApp.getFiles ();
var counter = 0;
while (files.hasNext () && counter <21) {
var file = files.next ();
var data = [
file.getName (),
file.getUrl (),
file.getOwner ()? file.getOwner (). getName (): 'Unknown'
];
var filter = data.filter (v => v [2] === 'Unknown');
counter ++;
st.appendRow (filter);
}
}
But the list of files won't retrieve.
It seems that the filter in while is not recommended. Or maybe, folks here have another solution.
Upvotes: 1
Views: 378
Reputation: 27390
I am not sure if this is the best approach.
But since you are getting an error here file.getOwner().getName()
when the owner does not exist, then try to use try...catch to catch the error.
Namely, if there is an error pass Unknown
, otherwise pass the name of the file owner.
function getfilesUnknown() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var st = ss.getActiveSheet();
var files = DriveApp.getFiles();
var counter = 0;
var data = [];
while (files.hasNext() && counter<21) {
var file = files.next();
try{
data.push([file.getOwner().getName()]);
}
catch(e){
data.push(['Unknown']);
}
counter++;
}
st.getRange(st.getLastRow()+1,1,data.length,1).setValues(data);
}
Please note that your code is not very well optimized. You add information in the data
array but then you filter on a particular value only. Therefore there is no need of using the other items as they will slow down your code.
Another note is that you are using appendRow
iteratively which is not recommended. Instead use setValues
outside of the for loop once.
Upvotes: 2