Skip to content

Instantly share code, notes, and snippets.

@diazabdulm
Last active March 10, 2021 00:57
Show Gist options
  • Save diazabdulm/3dbe617c0d356d9138bc4229e7c50bd1 to your computer and use it in GitHub Desktop.
Save diazabdulm/3dbe617c0d356d9138bc4229e7c50bd1 to your computer and use it in GitHub Desktop.
Automatically delete old Google Drive files and folders
// 1. Import the following into Google Apps Scripts
// 2. Select your desired execution interval
function getItemsOlderThan(numDays) {
const threshold = new Date().getTime() - 3600 * 1000 * 24 * numDays;
const cutoffDate = new Date(threshold).toISOString();
const query = `(modifiedDate < "${cutoffDate}") and ('me' in owners)`;
const response = Drive.Files.list({ q: query });
return response.items.map((item) => item.id)
}
function removeOldItems() {
const itemIDs = getItemsOlderThan(100);
itemIDs.forEach((id) => Drive.Files.remove(id));
}
@diazabdulm
Copy link
Author

diazabdulm commented Mar 10, 2021

Warning: This directly deletes the files, which is an irrecoverable process. To move your files and folders to the trash instead, change line 16 to:

itemIDs.forEach((id) => {
  const item = DriveApp.getFileById(id)
  item.setTrashed(true)
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment