Reputation: 189
I have multiple named spreadsheets in a folder on google drive. How would I get their id or url by passing one of the names to a function?
I can get the file using DriveApp, but I dont know how to get the id from that.
function getFile(name)
{
var folder = DriveApp.getFolderById('id');
var file = folder.getFilesByName(name);
//get file id
}
Is there a way to get the id or url using DriveApp or SpreadsheetApp?
Upvotes: 0
Views: 1331
Reputation: 3337
The command folder.getFilesByName(name);
potentially retrieve more than one file (has it's name say it- getFiles) so it give you a file iterator that you need to parse with a while loop.
If you are absolutely sure that there is at least one file with that has the name, you can avoid the loop with a little dirty code like this:
var file = folder.getFilesByName(name).next();
and then retrieve the id with:
var id = file.getId()
-- EDIT:
If you are not sure to retrieve a file (You don't know if it exist or has the right name....) you'll need to check the result of the file iterator.
Instead of writing :
var file = folder.getFilesByName(name);
prefer to write:
var files = folder.getFilesByName(name); // you could have zero or more than one file
And then you can do a while loop if you believe there is more than one file with that name:
var out = [];
while(files.hasNext()) {
var file = files.next();
out.push(file.getId());
Logger.log(file.getId());
}
return out;
or if there is only one or zero file a simple if will do the job:
if (files.hasNext()) {
var file = files.next();
Logger.log(file.getId());
return file.getIt(); // eventually
}
else {
Logger.log("there is no file with that name");
return "no id"; // eventually
}
Upvotes: 1