如何最好地删除文件夹及其子文件夹中的所有文件 [英] How best to delete all files in a folder and its subfolders

查看:164
本文介绍了如何最好地删除文件夹及其子文件夹中的所有文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

美好的一天.我试图获取文件夹和子文件夹中的所有文件并将其删除,但是代码不起作用,它仅通过第一个子文件夹,并且其中没有文件,脚本结束,请帮忙.

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)
  }
 }
} 

推荐答案

我相信您的目标如下.

  • 您要删除 1-2VAPBzEQxCaoN7KGSB_K_peiLIDk32e 文件夹中的所有文件.
    • 在这种情况下,您要将文件删除到垃圾箱.
    • 在您的脚本中,我认为从 1-2VAPBzEQxCaoN7KGSB_K_peiLIDk32e 文件夹下的文件夹中检索了文件.
      • 例如,如果 1-2VAPBzEQxCaoN7KGSB_K_peiLIDk32e 的文件夹中有2个文件夹,而2个文件夹中有1个文件和1个文件夹,其中每个文件夹中有1个文件,则脚本将检索2个文件.因为脚本从 1-2VAPBzEQxCaoN7KGSB_K_peiLIDk32e 文件夹下的文件夹中检索文件.
      • 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.

        当以上几点反映到脚本中时,它如下所示.

        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 功能扫描所有子文件夹中的所有文件,并删除这些文件.(它们已移至垃圾箱.)
        • 已删除文件的文件名显示在控制台中.
          • 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.
            • 在此脚本中,请在启用V8运行时时使用它.
            • 当文件数量很大时,首先,将检索文件ID,并且下一步,使用批处理请求删除文件可能是合适的.参考

            这篇关于如何最好地删除文件夹及其子文件夹中的所有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆