如何在共享的谷歌云端硬盘文件夹中使用谷歌应用脚本删除特定文件夹中的特定类型的文件(CSV 文件)



我在将文件添加到共享的Google云端硬盘文件夹时遇到问题,并且无法在我的脚本中删除任何类型的特定类型的文件。共享的谷歌云端硬盘文件给我带来了问题。下面的代码适用于我自己的个人谷歌驱动器文件夹,用于将CSV从一个谷歌驱动器文件夹添加和删除到我指定的任何其他文件夹。但是,它不适用于我们的常规共享Google云端硬盘文件夹。我已通过 Google Cloud Console API 获得云端硬盘和表格的授权权限,但我仍然遇到权限问题。如能就此问题提供任何帮助或澄清,将不胜感激。

下面是两个不同的代码段。第一个带有 moveFiles(( 函数的函数在我的个人驱动器上工作,但在共享文件夹中不起作用。这里还有一些我正在使用的代码,以更简单的方式测试共享文件夹。我能够获得 putFile(( 函数将 newDoc 放入共享的谷歌驱动器文件夹中,但无法将其删除。

function moveFiles(source_folder, dest_folder) 
{
// set current destination to grab the folder from
var currentFolder=DriveApp.getFolderById("1emSsRay_WI_z_qBUpQIoccxQID28FvB0");
// grab only the csv's within current folder
var docs = DriveApp.getFilesByType(MimeType.CSV);
// set target destination where we will store old csv's that have been processed & Analyzed 
var destination = DriveApp.getFolderById("1wYG1Gd5z0-nucedSMOBn8ZJs68ZgR8Hb");
// iterate through the csv's files within the currentFolder, add them to the destination and remove them from the current folder
while (docs.hasNext()) 
{ 
var doc = docs.next();
destination.addFile(doc); // get error "Cannot use this operation on a shared drive item(line 13, file "SharedDriveMove")
currentFolder.removeFile(doc);
}
}
function putFile()
{
var newDoc = DocumentApp.create('Testing Team Drive MoveTo').getId();
var file = DriveApp.getFileById(newDoc);
var moveFile = DriveApp.getFolderById('1emSsRay_WI_z_qBUpQIoccxQID28FvB0').addFile(file);
}
function takeFile()
{
var filesIterator = DriveApp.getFilesByName('Testing Team Drive MoveTo');
while (filesIterator.hasNext()) 
{
var file = filesIterator.next();
}
var cleanup = DriveApp.getFolderById('1wYG1Gd5z0-nucedSMOBn8ZJs68ZgR8Hb').addFile(file,{"supportsAllDrives": true}); // get error "Cannot find method addFile(File,Object).(line 15,file"Code")
var moveFile = DriveApp.getFolderById('1emSsRay_WI_z_qBUpQIoccxQID28FvB0').removeFile(file,{"supportsAllDrives": true});
}

DriveApp 是一个 Apps 脚本类,因此它在云端硬盘中具有局限性。另外,正如文档所述:

此方法不会删除文件,但如果从中删除文件 它的所有父项,除非通过搜索 它或使用"所有项目"视图。

您应该改用云端硬盘 API 执行此操作:

使用"supportsAllDrive",否则如果文件位于共享云端硬盘中,则找不到该文件(直到 2020 年弃用(。

Drive.Files.remove("your file ID", {"supportsAllDrives": true});

您还必须授权云端硬盘文件范围。

最新更新