I have this code, but this gives an error of cannot read property 'getName' of null how do I fix this. There are about 2000 files on my drive. There are files shared by other users as well.
function getMyFilesFromDrive() {
var myFiles = DriveApp.searchFiles('title contains "A3_"');
var sheet = SpreadsheetApp.getActive().getSheetByName("Files");
sheet.clear();
var rows = [];
rows.push(["ID", "Name", "Url", "user"]);
while(myFiles.hasNext()) {
var file = myFiles.next();
if(file != null) {
rows.push([file.getId(), file.getName(), file.getUrl(), file.getOwner().getName()]);
}
}
sheet.getRange(1,1,rows.length,4).setValues(rows);
}
CodePudding user response:
Find Spreadsheets
This is what I use:
function getSpreadsheets() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Files');
if (sh.getLastRow() > 1) {
const rg = sh.getRange(2, 1, sh.getLastRow() - 1, sh.getLastColumn());
rg.clearContent();
SpreadsheetApp.flush();
}
var token = '';
var vA = [["Id", "MimeType", "Kind", "Title", "Path", "OwnerEmails"]];
do {
let resp = Drive.Files.list({ pageToken: token, q: "mimeType='application/vnd.google-apps.spreadsheet'" });
token = resp.nextPageToken;
for (let i = 0; i < resp.items.length; i ) {
let item = resp.items[i];
if (item.title.match(/^A3_.*$/)) {//with names that begin with A3_
vA.push([item.id, item.mimeType, item.kind, item.title, getPathFromId(item.id), item.owners.map(function (o) { return o.emailAddress }).join(',')]);
}
}
if (token == '') {
ss.toast('That was the last ' resp.items.length '. Your Done!');
} else {
ss.toast('Another ' resp.items.length '. Keep Going!');
}
} while (token)
sh.getRange(2, 1, vA.length, vA[0].length).setValues(vA);
SpreadsheetApp.flush();
}
function getPathFromId(id) {
try {
var file = DriveApp.getFileById(id)
var pA = [];
pA.push(file.getName());
var folder = file.getParents();
while (folder.hasNext()) {
var f = folder.next();
pA.push(f.getName());
folder = f.getParents()
}
var r = pA.reverse().join(' / ');
}
catch (e) {
return e;
}
return r;
}
You will need to enable drive API.
You can add the downloadUrl to this
vA.push([item.id, item.mimeType, item.kind, item.title, getPathFromId(item.id), item.owners.map(function (o) { return o.emailAddress }).join(','),item.downloadUrl]);
and to the header here:
var vA = [["Id", "MimeType", "Kind", "Title", "Path", "OwnerEmails","Url"]];