Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching for file by name within a folder in google Drive using google scripts

In Google Drive I'm trying to search for a file in the current directory. The script is linked to a spreadsheet, so it finds the spreadsheet's parent directory, then uses its id to specify a search within the folder for a file named Title.

The code I have so far is:

function searchFolder(){

//get current folder id
var ss = SpreadsheetApp.getActive(); //current spreadsheet
var directParents = DriveApp.getFileById(ss.getId()).getParents();

while( directParents.hasNext() ) {
  var folder = directParents.next();
  var folderId = folder.getId();
  Logger.log(folder.getName() + " has id " + folderId);
}

//get files in folder
var parent = DriveApp.getFolderById(folderId); // folder Id
var search = 'name contains "Title"';
var specificFolder = parent.searchFiles(search);

while (specificFolder.hasNext()) {
  var file = specificFolder.next();
  Logger.log(file.getName());
  Logger.log(file.getId());
}
}

I get the error "Invalid argument: query" at the beginning of the while loop, which suggests that no files were found.

This error seems to only occur when I search by name. If I change the search variable to 'fullText contains "hello"' (the file Title has 'hello' in it) then there are no problems. What can be done to make the search by name work?

To replicate the error, make two spreadsheets in a folder on google drive. One spreadsheet has the script linked to it, the other is named "Title" and is being searched. Thanks.

like image 563
s_ll Avatar asked Jan 06 '23 13:01

s_ll


1 Answers

As Srikanth pointed, it is title contains not name contains. The code could be made simpler, please try the following code. You don't need a spreadhseet for this, just use simple Google Apps Script project file. Right click on empty space of your Drive ---> More ---> Google Apps Script

function SearchFiles() {
  //Please enter your search term in the place of Letter
  var searchFor ='title contains "Letter"';
  var names =[];
  var fileIds=[];
  var files = DriveApp.searchFiles(searchFor);
  while (files.hasNext()) {
    var file = files.next();
    var fileId = file.getId();// To get FileId of the file
    fileIds.push(fileId);
    var name = file.getName();
    names.push(name);

  }

  for (var i=0;i<names.length;i++){
    Logger.log(names[i]);
    Logger.log("https://drive.google.com/uc?export=download&id=" + fileIds[i]);

  }

}

Also check these links:

1) Search all documents in a folder 2)Search Drive Files

like image 82
Br. Sayan Avatar answered Jan 25 '23 02:01

Br. Sayan