How best to delete all files in a folder and its subfolders

Good day. I am trying to get all the files in the folder and subfolders and delete them, but the code does not work, it goes through only the first subfolder and there are no files in it, the script ends, please help.

function DeleteInvoices() {
 var folder = DriveApp.getFolderById("1-2VAPBzEQxCaoN7KGSB_K_peiLIDk32e");
 var fl = folder.getFolders();
 while (fl.hasNext()) {
 var files = fl.next();
 Logger.log(files)
 var fs = files.getFiles();
 while (fs.hasNext()) {
 var fss = fs.next();
 fss.setTrashed(true)
  }
 }
} 

Upvotes: 2

Views: 1617

Answers (1)

Tanaike
Tanaike

Reputation: 201438

I believe your goal as follows.

  • You want to remove all files in the folder of 1-2VAPBzEQxCaoN7KGSB_K_peiLIDk32e.
    • In this case, you want to remove the files to the trash box.
  • The folder of 1-2VAPBzEQxCaoN7KGSB_K_peiLIDk32e has subfolders and you want to remove all folders in all subfolders.
  • You don't want to remove the subfolders.

Modification points:

  • In your script, I think that the files from the folders just under the folder of 1-2VAPBzEQxCaoN7KGSB_K_peiLIDk32e are retrieved.
    • For example, if the folder of 1-2VAPBzEQxCaoN7KGSB_K_peiLIDk32e has 2 folders and the 2 folders has 1 file and 1 folder including 1 file in each folder, your script retrieves 2 files. Because the script retrieves the files from the folders just under the folder of 1-2VAPBzEQxCaoN7KGSB_K_peiLIDk32e.
  • In order to traverse all subfolders in 1-2VAPBzEQxCaoN7KGSB_K_peiLIDk32e, it is required to scan all folders including the subfolders in 1-2VAPBzEQxCaoN7KGSB_K_peiLIDk32e using the recursive loop.

When above points are reflected to the script, it becomes as follows.

Modified script:

function DeleteInvoices() {
  const getAllFiles = folder => {
    const files = folder.getFiles();
    while (files.hasNext()) {
      const file = files.next();
      console.log(file.getName());
      file.setTrashed(true);
    }
    const folders = folder.getFolders();
    while (folders.hasNext()) getAllFiles(folders.next());
  }

  var folder = DriveApp.getFolderById("1-2VAPBzEQxCaoN7KGSB_K_peiLIDk32e");
  getAllFiles(folder);
}
  • In this script, all files in all subfolders are scanned with the function of getAllFiles, and the files are removed. (They are moved to the trash box.)
  • The filenames of removed files are shown in the console.

Note:

  • In this script, please use it with enabling V8 runtime.
  • When the number of files are large, at first, the file IDs are retrieved, and as the next step, to remove the files using the batch request might be suitable. Ref

References:

Upvotes: 2

Related Questions