且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何删除 Google Drive 中的文件?

更新时间:2023-12-04 21:40:46

有 3 种服务可用于删除文件.

There are 3 services available to delete a file.

  • DriveApp - Apps 脚本内置
  • 高级驱动器服务 - 内置于 Apps 脚本,但必须启用.比 DriveApp 拥有更多功能
  • Google Drive API - 不是内置于 Apps 脚本,但可以使用 Drive REST API 和 UrlFetchApp.fetch(url,options)
  • 从 Apps 脚本中使用
  • DriveApp - Built-in to Apps Script
  • Advanced Drive Service - Built-in to Apps Script but must be enabled. Has more capability than DriveApp
  • Google Drive API - Not built-in to Apps Script, but can be used from Apps Script using the Drive REST API together with UrlFetchApp.fetch(url,options)

DocsList 服务现已弃用.

高级驱动器服务可用于删除文件而不将其发送到回收站.认真考虑无法找回已删除文件的风险.Advanced Drive Service 有一个 remove 方法,可以删除文件而不将其发送到垃圾文件夹.高级服务具有许多与 API 相同的功能,无需发出 HTTPS GET 或 POST 请求,也不需要 OAuth 库.

The Advanced Drive Service can be used to delete a file without sending it to the trash. Seriously consider the risk of not being able to retrieve the deleted file. 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, and not needing an OAuth library.

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 设置为开启.并且确保在您的 Google Cloud Platform 中启用 Drive API.如果它没有在BOTH 处打开,它将不可用.

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.