如何使用Google Apps脚本将文件夹从MyDrive复制到TeamDrive?

时间:2019-01-07 14:16:20

标签: google-apps-script google-drive-api google-drive-team-drive

我找到了以下Google Apps脚本,该脚本使我可以将文件夹从MyDrive复制到MyDrive,将SharedFolders复制到MyDrive:

function start() {

  var sourceFolder = "source";
  var targetFolder = "target";

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

}

我试图对其进行修改,以将文件夹从MyDrive复制到Teamdrive,但是我失败了,就像我是一个完整的菜鸟。有人可以帮我更新此目的吗?

2 个答案:

答案 0 :(得分:0)

下面的示例将文件移动到指定的文件夹(可以是团队驱动器)。目前还没有时间将其与您的代码集成,但是如果以后有空,我会发布更好的答案。希望对您有帮助

 //Move the new doc to the folder
  var fileId   = DriveApp.getFileById("<<FILEID>>");
  var folder = DriveApp.getFolderById("<<WHERE TO SAVE IT>>");
  var file = DriveApp.getFileById(fileId);

  folder.addFile(file);

答案 1 :(得分:0)

谢谢您的评论James。请记住,我要移动文件夹(而不是文件)。我设法在随机添加一些代码的过程中做到了这一点(我缺乏适当地添加它们的知识,因此我确信这是一件很糟糕的工作):

function start() {

  var sourceFolder = "A-folder-in-MyDrive";
  var targetFolder = "MY-TEAMDRIVE-ID";

  var source = DriveApp.getFoldersByName(sourceFolder);
  var target = DriveApp.getFolderById("MY-TEAMDRIVE-ID");

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

}

使用此代码,如果我在MyDrive中具有以下内容:

MyDrive / A-folder-in-MyDrive / MoreFolders / file.txt

然后在我的TeamDrive中创建以下内容: TeamDrive / MoreFolders / file.txt

因此,基本上,sourceFolder内的文件夹已复制到我的TeamDrive中!

现在,如果我还可以创建A-folder-in-MyDrive,不仅位于其中的子文件夹非常出色……任何帮助将不胜感激!