How to delete a File in Google Drive?

后端 未结 5 560
既然无缘
既然无缘 2020-12-31 03:57

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

This finds files:

var ExistingFiles = DocsList.find(fileName);

But Do

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-31 04:18

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

    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);
      };
    };
    

    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.

    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.

提交回复
热议问题