J.Doe
J.Doe

Reputation: 339

Google Apps Script returning all files in Drive, rather than files in a folder

I have a folder in Google Drive, where there are some files. I want to retrieve all of these file information, and that's all I want. There are many other files in other folders, but I don't need them. However, my following code is showing all files' names. How can I limit the result only to the files in the specified folder?

//Folder ID
var myFolderId = "XXXXXXXXXXXXXXXXXXXXXXXXX";
var files = DriveApp.getFolderById(myFolderId).getFiles();
while(files.hasNext())
{
    var file = files.next();
    Logger.log(file.getName());
}

For now, there are only 4 files in this folder, but the log shows the entire file names in my Google Drive. I don't know what I am doing wrong, because I am specifying the folder with ID. How come it is returning every file in Google Drive?

Upvotes: 1

Views: 565

Answers (1)

Rafa Guillermo
Rafa Guillermo

Reputation: 15377

Answer:

Your code already works great!

Further information:

Google Apps Script doesn't allow the running of global code as specific functions need to be declared and run, at least, not in the same was as locally-run code. The global variables are static and can not be changed in the runtime.

Things you can do:

As Cooper mentioned in their comment - all you need to do is put your code in a function, call the function and you're set. The code works great:

function functionName(){
  var myFolderId = "XXXXXXXXXXXXXXXXXXXXXXXXX";
  var files = DriveApp.getFolderById(myFolderId).getFiles();
  while(files.hasNext())
  { 
    var file = files.next();
    Logger.log(file.getName());
  }
}

As a side-note: if you really want to use a global scope (or at least. use an emulation of it), the PropertiesService is available to you, though you'd still have to set them in a function and run a function to retrieve them:

function setVars(){
  PropertiesService.getScriptProperties().setProperty('myFolderId', 'XXXXXXXXXXXXXXXXXXXXXXXXX');
}
function listFiles(){
 var files = DriveApp.getFolderById(PropertiesService.getScriptProperties().getProperty('myFolderId')).getFiles();
 //continue this code
}

Upvotes: 1

Related Questions