Google Drive - How to empty trash from code (progr

2019-01-26 16:52发布

问题:

Please help me to integrate a project with Google Drive. The problem is that Google Drive trash folder is never emptied, so eventually Google Drive synchronization with desktop stops working due to the lack of space.

I need either to configure the trash to not keep deleted files (preferred option) or empty it programatically from C# code (less preferred), or other programing language (last resort option) .

How do I empty Google Drive trash from code or script or whatever?

回答1:

The Google Drive API doesn't expose a method to empty the trash but it has a delete method to delete files permanently, without sending them into the trash:

https://developers.google.com/drive/v2/reference/files/delete

You can also retrieve files from trash by checking the trashed label of the Files resource and then call delete on them.



回答2:

Here a shorter version, i tried using the above solution, but with no luck.

function emptydrivetrash() {
  Drive.Files.emptyTrash();
}

All you have to do is to enable de drive api, in the Resources Menu-> Google Advanced Services and in google developers's console...



回答3:

Here is a complete solution:

1) Create an empty script on your drive

2) Paste the following code:

function doGet() {
  try{
  authorize();    
  var key = "YOUR DEVELOPER KEY";
  var params = {method:"DELETE",
                oAuthServiceName: "drive",
                oAuthUseToken: "always"
               };  
  UrlFetchApp.fetch("https://www.googleapis.com/drive/v2/files/trash?key="+key,     params);  
  }
  catch(error)
  {
    MailApp.sendEmail("<some email>", "EMPTY TRASH BIN ERROR:<br>"+error);    
    return;
  } 
}

function authorize() {
  var oauthConfig = UrlFetchApp.addOAuthService("drive");
  var scope = "https://www.googleapis.com/auth/drive";
  oauthConfig.setConsumerKey("anonymous");
  oauthConfig.setConsumerSecret("anonymous");
  oauthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?     scope="+scope);
  oauthConfig.setAuthorizationUrl("https://accounts.google.com/OAuthAuthorizeToken");    
  oauthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");  
}

3) Deploy the script as a web application

4) Click on the clock on the top bar and create a trigger that invokes the doGet method

This will empty the trash for the user that is creating the trigger.