如何删除Google云端硬盘中的文件? [英] How to delete a File in Google Drive?

查看:1445
本文介绍了如何删除Google云端硬盘中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何编写删除文件的Google Apps脚本?

How do I write a Google Apps Script that deletes files?

这会找到文件:

var ExistingFiles = DocsList.find(fileName);

但是 DocsList.deleteFile 不存在删除文件。

是否可以将这些文件移动到另一个文件夹或垃圾箱?

Is there a way to move those files to another Folder or to Trash?

我会考虑的其他解决方法是能够覆盖具有相同名称的现有文件。

The other workaround I would consider is to be able to override an existing file with the same name.

当前,当我想创建一个名称已在MyDrive中使用的文件时,它会创建另一个同名文件。我想保留1个文件(保留一个新文件,而丢失一个旧文件)。

Currently when I want to create a file with a name already used in MyDrive then it creates a second file with the same name. I would like to keep 1 file (the new one is kept and the old one is lost).

推荐答案

DocsList 服务现已弃用。此答案使用更新的 DriveApp 服务。

The DocsList service is now deprecated. This answer uses the newer DriveApp service.

您还可以使用高级驱动器服务,该服务可用于删除文件而无需将其发送到垃圾箱。您可能需要删除文件而不将其发送到垃圾箱,以避免以后清空垃圾箱文件夹。高级驱动器服务具有删除方法,该方法删除文件而不将其发送到回收站文件夹。高级服务具有与API相同的功能,无需发出HTTPS GET或POST请求。

You can also use the Advanced Drive Service, which can be used to delete a file without sending it to the trash. You may want to delete a file without sending it to the trash, in order to avoid emptying the trash folder later. The Advanced Drive Service has a remove method which removes a file without sending it to the trash folder. Advanced services have many of the same capabilities as the API's, without needing to make an HTTPS GET or POST request.

function delteFile(myFileName) {
  var allFiles, idToDLET, myFolder, rtrnFromDLET, thisFile;

  myFolder = DriveApp.getFolderById('Put_The_Folder_ID_Here');

  allFiles = myFolder.getFilesByName(myFileName);

  while (allFiles.hasNext()) {//If there is another element in the iterator
    thisFile = allFiles.next();
    idToDLET = thisFile.getId();
    //Logger.log('idToDLET: ' + idToDLET);

    rtrnFromDLET = Drive.Files.remove(idToDLET);
  };
};

这结合了DriveApp服务和Drive API来删除文件而不将其发送到垃圾箱。 Drive API方法 .remove(id)需要文件ID。如果文件ID不可用,但文件名可用,则可以先按名称查找文件,然后获取文件ID。

This combines the DriveApp service and the Drive API to delete the file without sending it to the trash. The Drive API method .remove(id) needs the file ID. If the file ID is not available, but the file name is, then the file can first be looked up by name, and then get the file ID.

要使用DriveAPI,您需要需要通过资源高级Google服务菜单进行添加。将Drive API设置为 ON AND 确保在您的Google Cloud Platform中已启用Drive API。如果未在两个位置中将其打开,则将不可用。

In order to use DriveAPI, you need to add it through the Resources, Advanced Google Services menu. Set the Drive API to ON. AND make sure that the Drive API is turned on in your Google Cloud Platform. If it's not turned on in BOTH places, it won't be available.

这篇关于如何删除Google云端硬盘中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆