Last active
April 2, 2023 16:34
-
-
Save burak-kara/1c85ec7c10c8c9811d31c8e8431477c0 to your computer and use it in GitHub Desktop.
Google Drive - Remove duplicate files (files with the same name) from a folder and its subfolders. Keeps only one copy. Also, deletes a folder if it becomes empty
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Put the ID of the folder you want to process | |
// https://drive.google.com/drive/folders/abcdefgh | |
const id = "abcdefgh"; | |
// we will store file names in this dictionary. | |
// using Set could be more efficient to check if it contains file (time complexity: O(1)) | |
// App Script does not support Set | |
const allFiles = []; | |
// Keep deleted file URLs and report in the end | |
const deletedURLs = []; | |
function start() { | |
const folder = DriveApp.getFolderById(id); | |
iterateFolder(folder); | |
handleSubFolders(folder); | |
prune(folder); | |
Logger.log("Deleted file and folder URLs:\n" + deletedURLs); | |
} | |
function handleSubFolders(parent) { | |
const subFolders = parent.getFolders(); | |
if (subFolders.hasNext()) { | |
while (subFolders.hasNext()) { | |
const subFolder = subFolders.next(); | |
iterateFolder(subFolder); | |
handleSubFolders(subFolder); | |
} | |
} | |
} | |
// Iterate files in a folder | |
function iterateFolder(folder) { | |
const files = folder.getFiles(); | |
if (files.hasNext()) { | |
while (files.hasNext()) { | |
const file = files.next(); | |
const fileName = file.getName(); | |
if (allFiles.includes(fileName)) { | |
deletedURLs.push(file.getUrl()); | |
file.setTrashed(true); | |
} else { | |
allFiles.push(fileName); | |
} | |
} | |
} | |
} | |
// Delete folders if they do not have any folder or file after operations above | |
function prune(folder) { | |
const subFolders = folder.getFolders(); | |
while (subFolders.hasNext()) { | |
prune(subFolders.next()); | |
} | |
if (!folder.getFiles().hasNext() && !subFolders.hasNext()) { | |
folder.setTrashed(true); | |
deletedURLs.push(folder.getUrl()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment