Skip to content

Instantly share code, notes, and snippets.

@xr1337

xr1337/Code.gs

Last active Jul 2, 2020
Embed
What would you like to do?
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