Skip to content

Instantly share code, notes, and snippets.

@xr1337
Last active July 2, 2020 09:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xr1337/77568ec7ce2c9cd81dcb6daf87f2286a to your computer and use it in GitHub Desktop.
Save xr1337/77568ec7ce2c9cd81dcb6daf87f2286a to your computer and use it in GitHub Desktop.
Google script to clean up root drive folder. All files are moved to their extension( mimetype) folder
/// returns extension from the file object
/// Queries the mimetype
const getExtension = function(file) {
var mime = file.getMimeType()
var docType = mime.split("/").pop()
return docType.split(".").pop()
};
/// send an email to myself when any files are moved
const notify = function(moved, log) {
MailApp.sendEmail({
to: Session.getActiveUser().getEmail(),
subject: `Clean Up Root Drive folder - ${moved} files move`,
htmlBody: `The following files have been moved: ${log}`,
});
}
/// main
function CleanUpRootDrive() {
const rootFolder = DriveApp.getRootFolder()
const folders = rootFolder.getFolders()
const rootFiles = rootFolder.getFiles()
// Create a fast lookup for foldername
var folderNameMap = {}
while(folders.hasNext()) {
const folder = folders.next()
folderNameMap[folder.getName()] = folder
}
// iterate to all files in the root folder
// and move them to their extensions folder
var moved = 0
var log = ""
while(rootFiles.hasNext()) {
const file = rootFiles.next()
var ext = getExtension(file)
var folder = folderNameMap[ext]
if( !folder ) {
folder = rootFolder.createFolder(ext)
folderNameMap[ext] = folder
}
/// Only move the folder if current user is the owner
if(file.getAccess(Session.getActiveUser()) == DriveApp.Permission.VIEW) {
continue
}
if(file.getAccess(Session.getActiveUser()) == DriveApp.Permission.COMMENT) {
continue
}
file.moveTo(folder)
log += `<br> - [${file.getName()}] moved to folder [${ext}].`
moved ++
}
if(moved > 0 ) {
notify(moved, log)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment