Created
October 13, 2024 12:38
-
-
Save rbrown256/ff5b38058f3e53c59018a9dcbb50e80d to your computer and use it in GitHub Desktop.
Move files in Google Drive and take ownership
This file contains 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
function copyAndDeleteFiles(sourceFolderId, destinationFolderId) { | |
// Get the source and destination folders. | |
var sourceFolder = DriveApp.getFolderById(sourceFolderId); | |
var destinationFolder = DriveApp.getFolderById(destinationFolderId); | |
// Get all files in the source folder. | |
var files = sourceFolder.getFiles(); | |
// Copy each file to the destination folder and then delete older files with the same name. | |
while (files.hasNext()) { | |
var file = files.next(); | |
// Make a copy of the file in the destination folder | |
var copiedFile = file.makeCopy(file.getName(), destinationFolder); | |
console.log('Copied file: ' + file.getName() + " to " + destinationFolder.getName()); | |
// Find and delete older files with the same name in the destination folder | |
var fileName = file.getName(); | |
var existingFiles = destinationFolder.getFilesByName(fileName); | |
var newestFileDate = copiedFile.getDateCreated(); | |
while (existingFiles.hasNext()) { | |
var existingFile = existingFiles.next(); | |
if (existingFile.getDateCreated() < newestFileDate) { | |
console.log('Deleting older file: ' + existingFile.getName()); | |
existingFile.setTrashed(true); // Or existingFile.delete(); for permanent deletion | |
} | |
} | |
// Remove the original file from the source folder | |
sourceFolder.removeFile(file); | |
console.log('Removed file: ' + file.getName() + " from " + sourceFolder.getName()); | |
} | |
console.log('Finished copying and deleting files.'); | |
} | |
function main() { | |
// TODO: | |
// copyAndDeleteFiles('source_id', 'dest_id'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment