Reputation: 53
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
Reputation: 201438
I believe your goal as follows.
1-2VAPBzEQxCaoN7KGSB_K_peiLIDk32e
.
1-2VAPBzEQxCaoN7KGSB_K_peiLIDk32e
has subfolders and you want to remove all folders in all subfolders.1-2VAPBzEQxCaoN7KGSB_K_peiLIDk32e
are retrieved.
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
.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.
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);
}
getAllFiles
, and the files are removed. (They are moved to the trash box.)Upvotes: 2