复制文件夹中的所有文件,包括子文件夹中的文件

时间:2019-12-04 10:04:34

标签: google-apps-script

我必须复制原始文件夹中存在的每个子文件夹的文件,但是当前正在复制最后一个子文件夹的文件,而正在创建的其余子文件夹的文件为空,但是在原始文件中却没有文件复制。

例如,有一个主文件夹Amit-> amit1子文件夹-> amit2子文件夹,例如,当前它仅复制amit 2子文件夹的文件,其余文件夹为空

var sheet = SpreadsheetApp.getActiveSheet();
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var scriptproperties = PropertiesService.getScriptProperties();

function authorize() {
    spreadsheet.toast("Enter Folder ID and  Select GDrive: Copy Folder->  Make a Copy", "", -1);

}


function onOpen() {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var menuEntries = [{
            name: "1. Authorize",
            functionName: "authorize"
        }, {
            name: "2. Make a Copy",
            functionName: "findRootFolder"
        }

    ];
    ss.addMenu("GDrive: Copy Folder", menuEntries);
    spreadsheet.toast("Select GDrive: Copy Folder-> Authorize. This is an One Time Action.", "Get Started", -1);
}

function findRootFolder() {
    var folderId = sheet.getRange("B5").getValue();
    var folderId = folderId.toString().trim();
    var start = new Date();

    try {

        var topFolder = DriveApp.getFolderById(folderId);

        deletekeys();
        spreadsheet.toast("Copy Process Has Started. Please Wait...", "Started", -1);
        getFolders_(topFolder.getName(), topFolder);
        spreadsheet.toast("Folder Has Been Copied Successfully. Please Check Your Google Drive Now.", "Success", -1);
    } catch (e) {
        Browser.msgBox("Error", "Sorry, Error Occured: " + e.toString(), Browser.Buttons.OK);
        spreadsheet.toast("Error Occurred :( Please make sure you Entered Folder ID in B5 Cell.", "Oops!", -1);
    }

}

function getFolders_(path, container) {

    var folders = container.getFolders();

    var count = 0;
    while (folders.hasNext()) {
        count++;
        var folder = folders.next();
    }

    var folderCount = count;
    var fileslist = container.getFiles();
    var fileCountFind = 0;
    while (fileslist.hasNext()) {
        fileCountFind++;
        var file = fileslist.next();
        Logger.log(file.getName());
    }
    var fileCount = fileCountFind;
    var files = container.getFiles();

    Logger.log("container.getName() " + container.getName() + "| folder length " + folderCount + "| files length " + fileCount);

    if (folderCount <= 0) {

        if (fileCount > 0) {
            Logger.log("Just Files Found Loop");
            copyfiles_(container.getName(), files);
        }
    }

    if (folderCount) {
        Logger.log("If loop, Folders Found");
        var folders = container.getFolders();

        while (folders.hasNext()) {

            var folder = folders.next();
            copy_(container.getName(), folder.getName(), files);
            var thisFolder = folder.getName();
            var thisPath = path + "/" + thisFolder;
            Logger.log("Folder Name:" + folder.getName());
            getFolders_(thisPath, folder);

        }

    }
    return;
}

function copy_(containername, childname, files)

{

    if (scriptproperties.getProperty(containername + "copy")) {
        Logger.log("if");
        var parentcontainer = DriveApp.getFolderById(scriptproperties.getProperty(containername + "copy"));

        if (!scriptproperties.getProperty(containername + "processed")) {
            /*process, copy files*/

            while (files.hasNext()) {
                var file = files.next();
                var newFile = file.makeCopy(file.getName(), parentcontainer);
               //parentcontainer.addFile(newFile);
                DriveApp.getRootFolder().removeFile(newFile);
                Utilities.sleep(2000);
            }




        }

        scriptproperties.setProperty(containername + "processed", "true");
        var childfolder = parentcontainer.createFolder(childname + "_copy");
        var childfolderid = childfolder.getId();
        scriptproperties.setProperty(childname + "copy", childfolderid);

    } else {

        Logger.log("else");
        var parentfold = DriveApp.createFolder(containername + "_copy");
        var parentfoldid = parentfold.getId();
        scriptproperties.setProperty(containername + "copy", parentfoldid);



        if (!scriptproperties.getProperty(containername + "processed")) {
            /*process, copy files*/

            while (files.hasNext()) {
                var file = files.next();
                var newFile = file.makeCopy(file.getName(), parentfold);
            //  parentfold.addFile(newFile);
                DriveApp.getRootFolder().removeFile(newFile);
                Utilities.sleep(2000);
            }

        }

        scriptproperties.setProperty(containername + "processed", "true");
        var childfolder = parentfold.createFolder(childname + "_copy");
        var childfolderid = childfolder.getId();
        scriptproperties.setProperty(childname + "copy", childfolderid);

    }
    Logger.log("Container Name: " + containername + "||" + " Child Name: " + childname);
}

function copyfiles_(containername, files) {
    if (scriptproperties.getProperty(containername + "copy")) {
        Logger.log("If Loop, Just files found- down");
        var parentcontainer = DriveApp.getFolderById(scriptproperties.getProperty(containername + "copy"));

        if (!scriptproperties.getProperty(containername + "processed")) {

            while (files.hasNext()) {
                var file = files.next();
                var newFile = file.makeCopy(file.getName(), parentcontainer);
              //parentcontainer.addFile(newFile);
                DriveApp.getRootFolder().removeFile(newFile);
                Utilities.sleep(2000);
            }
        }
        scriptproperties.setProperty(containername + "processed", "true");

    } else {

        Logger.log("Else Loop, Just files found");
        var parentfold = DriveApp.createFolder(containername + "_copy");
        var parentfoldid = parentfold.getId();
        scriptproperties.setProperty(containername + "copy", parentfoldid);

        if (!scriptproperties.getProperty(containername + "processed")) {

            while (files.hasNext()) {
                var file = files.next();
                var newFile = file.makeCopy(file.getName(), parentfold);
              //parentfold.addFile(newFile);
                DriveApp.getRootFolder().removeFile(newFile);
                Utilities.sleep(2000);
            }



        }
        scriptproperties.setProperty(containername + "processed", "true");
    }

}

function deletekeys() {
    scriptproperties.deleteAllProperties();
}

1 个答案:

答案 0 :(得分:0)

根据您的问题,我了解到您想在文件结构中复制文件,而忽略文件夹。 我想出了一个递归函数的示例,它从传递的文件夹到最后一个子文件夹,并复制它遇到的每个文件,然后将其移动到主文件夹(通过参数传递的文件,而不是主驱动器文件夹):

 function myFunction() {

  var fromFolder = '***your folder's ID***';
  var toFolder = fromFolder

  // THIS WILL MAKE COPIES OF ALL THE FILES IGNORING THE FOLDER STRUCTURE INTO toFolder
  copyFiles(fromFolder, toFolder)
}

function copyFiles(idToSearch, mainId) {
  var file = Drive.Files.get(idToSearch)

  //CHECKS IF THE FOLDER PASSED IS AN ACTUAL FOLDER OR A FILE
  if (file.mimeType != 'application/vnd.google-apps.folder') {
    Logger.log(file.parents[0].id)

    // COPY THE FILE
    var copyFile = DriveApp.getFileById(file.id).makeCopy();


    //Drive.Files.copy(file, file.id)

    //UPDATES THE FILE PARENT TO THE ROOT FOLDER
    var optionalArgs = {   
      "addParents": mainId,
      "removeParents": copyFile.getParents().next().getId()
    }
    Drive.Files.patch(Drive.Files.get(copyFile.getId()), copyFile.getId(), optionalArgs)

  } else {

    var fileChildren = Drive.Children.list(file.id)

    for(var i = 0; i < fileChildren.items.length; i++) {
      copyFiles(fileChildren.items[i].id, mainId)
    }
  }

}

如果那不是您所需要的,请告诉我。


编辑

我找到并尝试了此代码,它可以工作。

信用:Make a Copy of Folders in Google Drive with Google Scripts

function start() {

  var sourceFolder = "Copy folder structure";
  var targetFolder = "New folder structure Copy";

  var source = DriveApp.getFoldersByName(sourceFolder)
  var target = DriveApp.createFolder(targetFolder);

  if (source.hasNext()) {
    copyFolder(source.next(), target);
  }

}

function copyFolder(source, target) {

  var folders = source.getFolders();
  var files   = source.getFiles();

  while(files.hasNext()) {
    var file = files.next();
    file.makeCopy(file.getName(), target);
  }

  while(folders.hasNext()) {
    var subFolder = folders.next();
    var folderName = subFolder.getName();
    var targetFolder = target.createFolder(folderName);
    copyFolder(subFolder, targetFolder);
  }  

}