如何用Google App Script的DriveApp永久删除Google Drive文件
如何通过Google Apps Script永久删除Google Drive文件
你说得没错,DriveApp.removeFile() 方法只是把文件从指定文件夹中移除,并不会真正删除文件——这些文件依然会留在Drive的「所有文件」列表或回收站里,自然能被搜索到。如果想要永久删除文件,你需要借助Google Drive API的核心功能,下面两种方法都可以在GAS中实现:
方法一:使用Google Apps Script高级服务(推荐)
Google Apps Script提供了封装好的高级Drive服务,比直接调用HTTP接口更简洁易用。
步骤1:启用高级Drive服务
在GAS编辑器中操作:
- 点击菜单栏的「扩展程序」>「高级Google服务」
- 在弹出窗口中找到「Drive API」,将开关拨至开启状态,点击「确定」
步骤2:编写永久删除代码
直接使用以下示例代码,传入目标文件ID即可调用:
function permanentlyDeleteFile(fileId) { try { // 调用高级服务的删除方法永久移除文件 Drive.Files.remove(fileId); console.log(`文件 ${fileId} 已被永久删除`); } catch (e) { console.error(`删除失败:${e.message}`); } }
方法二:使用UrlFetchApp调用Drive API
如果你不想启用高级服务,也可以直接通过HTTP请求调用Drive API的Files: delete端点,需要处理OAuth授权:
function permanentlyDeleteFileViaFetch(fileId) { const url = `https://www.googleapis.com/drive/v3/files/${fileId}`; const options = { method: 'DELETE', headers: { 'Authorization': `Bearer ${ScriptApp.getOAuthToken()}` } }; try { const response = UrlFetchApp.fetch(url, options); if (response.getResponseCode() === 204) { console.log(`文件 ${fileId} 已被永久删除`); } else { console.error(`删除失败,响应码:${response.getResponseCode()}`); } } catch (e) { console.error(`删除失败:${e.message}`); } }
重要注意事项
- 你必须拥有文件的所有者权限才能永久删除它;若仅为编辑者权限,只能将文件移至自己的回收站,无法彻底删除。
- 永久删除的文件无法恢复,调用前务必确认目标文件正确。
- 首次运行脚本时,会触发权限授权请求,需要允许GAS访问你的Drive文件。
内容的提问来源于stack exchange,提问作者charles bell
相关产品推荐
相关产品推荐

