将文件移动到Google云端硬盘中的其他文件夹

问题描述

在Google表格中,我有2列: A)“ Google云端硬盘文件ID” B)“新文件路径”。

我喜欢一个脚本,该脚本可以根据单元格中的路径将文件移动到该路径。如果该文件夹不存在,则可以创建该文件夹。

我找到了此脚本“ Move File to a Different Folder in Google Drive”,但需要帮助才能使其在表格中正常工作

解决方法

您基本上需要两个功能,但是只需要运行其中一个即可;这是主要功能。

说明:

功能 fileMover 将负责文件的移动:

function fileMover(id,targetFolderId,parentFolderId) {

  const file = DriveApp.getFileById(id)
  file.getParents().next().removeFile(file);
    try {
      DriveApp.getFolderById(targetFolderId).addFile(file);}
    
    catch(e){
      const parentFolder=DriveApp.getFolderById(parentFolderId);
      const newFolder=parentFolder.createFolder(file.getName() + " folder");
      DriveApp.getFolderById(newFolder.getId()).addFile(file);    
    }
}

函数 main 将遍历各列,并对文件中的每一行执行 fileMover

function main () {

  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName('Sheet1');
  const parentFolderId = 'parentfoldeidhere'; 
  const file_ids = sh.getRange("A2:A"+sh.getLastRow()).getValues().flat([1]);
  const folder_ids = sh.getRange("B2:B"+sh.getLastRow()).getValues().flat([1]);
  
  for (var i = 0 ; i < file_ids.length ; i++){
  fileMover(file_ids[i],folder_ids[i],parentFolderId)
  }
}

重要信息:

如您在 main 函数中所见,有一个变量 parentFolderId 。当 B列(文件夹ID)未提供正确的ID时,此文件夹用作所有正在创建的新文件夹的占位符。这是将文件组织在一个“父”文件夹中的一种较好做法。

这是我的电子表格文件的结构。 A列提供了您要移动的文件ID的列表。并且 B列提供了要在同一行中移动文件的文件夹ID的列表。如果 B列提供了错误的文件夹ID,则将在父文件夹中创建一个新文件夹(在 main 函数中调整父文件夹ID)。新文件夹的名称为nameofthefile + " folder",但也可以在file.getName() + " folder"函数的fileMover行中进行调整。另外,请随意调整工作表的名称,在本例中为 Sheet1

example