【问题标题】:Folder ,SubFolders and files count in google apps script谷歌应用程序脚本中的文件夹、子文件夹和文件计数
【发布时间】:2021-09-23 17:38:36
【问题描述】:

我们有一个共享文件夹。我们不知道有多少文件夹、子文件夹和文件,我们需要计算 google 应用脚本中的文件夹和文件

【问题讨论】:

    标签: google-apps-script


    【解决方案1】:

    我相信你的目标如下。

    • 您想计算特定文件夹(即共享文件夹)中的文件夹和文件数。在这种情况下,包括子文件夹。
    • 您希望使用 Google Apps 脚本实现此目的。

    在这种情况下,下面的示例脚本怎么样?

    示例脚本:

    请将以下脚本复制并粘贴到 Google Apps Script 的脚本编辑器中,并设置您要检查的文件夹的 top folderID。并且,请运行myFunction

    function myFunction() {
      const countFilesFolders = (folder, obj = {files: [], folders: []}) => {
        obj.folders.push(folder);
        const files = folder.getFiles();
        while (files.hasNext()) obj.files.push(files.next());
        const folders = folder.getFolders();
        while (folders.hasNext()) countFilesFolders(folders.next(), obj);
        return {fileCount: obj.files.length, folderCount: obj.folders.length - 1};
      }
    
      const topFolderId = "###"; // Please set the top folder ID of the folder you want to check.
      const res = countFilesFolders(DriveApp.getFolderById(topFolderId));
      console.log(res)
    }
    
    • 当这个脚本运行时,得到如下结果。

        { fileCount: ##, folderCount: ## }
      

    注意:

    • 在此脚本中,假设您有访问该文件夹的权限。请注意这一点。

    参考资料:

    【讨论】:

      【解决方案2】:

      请从谷歌表中尝试以下代码。 您将获得所有文件夹/文件/子文件夹/文件的列表

      function ListarTodo() {
        // List all files and sub-folders in a single folder on Google Drive, and get the name of the activesheet to know the folder desired.
        var foldername = "xxxxx"; //feed the folder name here
      
        var sheet = SpreadsheetApp.getActiveSheet();
        sheet.appendRow(["Carpeta","Nombre Archivo", "Fecha ultima modificacion", "Tamaño MB", "URL", "ID", "Descripción", "Tipo archivo"]);
      
        // getFoldersByName = Gets a collection of all folders in the user's Drive that have the given name.
        // folders is a "Folder Iterator" but there is only one unique folder name called, so it has only one value (next)
        var folders = DriveApp.getFoldersByName(foldername);
        var foldersnext = folders.next();
        var lintotal = 2;
      
        //Iniciamos la funcion recursiva // Initiate recursive function
        lintotal = SubCarpetas(foldersnext, foldername, lintotal);  
      }
      
      function SubCarpetas(folder, path, cantlineas) {
        cantlineas = ListarArchivos(folder, path, cantlineas);
        var subfolders = folder.getFolders();
      
        while (subfolders.hasNext()) {
          var mysubfolders = subfolders.next();
          var mysubfolderName = mysubfolders.getName(); 
          var newpath = "";
          newpath = path + "/" + mysubfolderName;
          cantlineas = SubCarpetas(mysubfolders, newpath, cantlineas);
        }
        return(cantlineas) 
      }
      
      function ListarArchivos(mifoldersnext, mipath, milintotal) {
        var datos = []; //array temporal que vamos a usar para grabar en la hoja
        var files = []; //array con todos los archivos que encontramos en la carpeta que estamos evaluando
        var file = []; //array que usamos para volcar los datos de cada archivo antes de guardarlo
        var total = 0;
        var sheet = SpreadsheetApp.getActiveSheet();
        var myfiles = mifoldersnext.getFiles();
      
      // Creamos un array con los datos de cada archivo y guardamos el total de archivos
      while (myfiles.hasNext()) {
          files.push(myfiles.next());
          total++;
      }
      //ordenamos el array por nombre de archivo alfabeticamente  //sorts the files array by file names alphabetically
      files = files.sort(function(a, b){
         var aName = a.getName().toUpperCase();
         var bName = b.getName().toUpperCase();
         return aName.localeCompare(bName);
      });
      
      ////
      var vuelta = 0;
      var bulk = 10; //Definimos la cantidad de lineas a grabar cada vez, en la hoja de la planilla GoogleDoc
      var linea = milintotal; //definimos en que linea vamos a grabar en la planilla
      for (var i = 0; i < files.length; i++) { //recorremos el array de archivos y formateamos la informacion que necesitamos para nuestra planilla
          file = files[i];
          var fname = file.getName(); //nombre del archivo
          var fdate = file.getLastUpdated(); //fecha y hora ultima modificacion
          var fsize = file.getSize()/1024/1024; //tamaño del archivo, lo pasamos de byte a Kbyte y luego a Mb
          fsize = +fsize.toFixed(2); //lo formateamos a dos decimales
          var furl = file.getUrl(); //url del archivo
          var fid = file.getId(); //id del archivo
          var fdesc = file.getDescription(); //descripcion
          var ftype = file.getMimeType(); //tipo de archivo
          datos[vuelta] = [mipath+" ("+total+")", fname, fdate, fsize, furl, fid, fdesc, ftype]; //ponemos todo dentro de un array temporal
          vuelta++;
          if (vuelta == bulk) {//cuando alcanza la cantidad definida, guarda este array con 10 lineas y lo vacía
            linea = milintotal;
      //      Logger.log("linea = "+linea); //DEBUG
      //      Logger.log("vuelta = "+vuelta); //DEBUG
      //      Logger.log("total = "+total); //DEBUG
      //      Logger.log("lintotal = "+milintotal); //DEBUG
      //      Logger.log("registros en datos = "+datos.length); //DEBUG
      //      Logger.log("data = "+datos); //DEBUG
            sheet.getRange(linea, 1, bulk,8).setValues(datos); //guardamos los datos del array temporal en la hoja
            SpreadsheetApp.flush(); //forzamos que aparezcan los datos en la hoja - sin esto los datos no aparecen hasta terminar (genera mucha impaciencia)
            milintotal = milintotal + vuelta;
            datos = []; //vaciamos el array temporal
            vuelta = 0;
            }
          }
      
      if (datos.length>0) {//Al salir del bucle grabamos lo que haya quedado en el array datos
            linea = milintotal;
      //      Logger.log("linea = "+linea); //DEBUG
      //      Logger.log("vuelta = "+vuelta); //DEBUG
      //      Logger.log("total = "+total); //DEBUG
      //      Logger.log("lintotal = "+milintotal); //DEBUG
      //      Logger.log("registros en datos = "+datos.length); //DEBUG
      //      Logger.log("data = "+datos); //DEBUG
            sheet.getRange(linea, 1, datos.length,8).setValues(datos);
            SpreadsheetApp.flush(); //ansiolítico
            milintotal = milintotal + datos.length;
            datos = [];
            vuelta = 0;
          }
      return (milintotal)
      }
      
      

      【讨论】:

        猜你喜欢
        • 2015-01-20
        • 1970-01-01
        • 1970-01-01
        • 2015-07-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-28
        • 1970-01-01
        相关资源
        最近更新 更多