Reputation: 11
I'm looking to make use of a script that will make a copy of any new files that are added to Google Drive -> Shared Drive -> (Drive name)
Ideally, I would like this copy to be moved to another Shared Drive and not have the title "Copy of "
inserted before the name ... but I'm not sure if it can be. (Side note: I can't get this to work... maybe it's because the other shared drive is owned by another?)
One of my problems is that I don't understand how to limit the copy function to only files that are newly added vs. added after a certain date.
All of my tests have led to a complete copy of the folder. I can't seem to limit it to new files. Also, I can't seem to avoid the addition of "Copy of " added to the start of each new file name.
What I have been able to get to work: I can (yes) copy the entire contents (all dates) of any given folder to a folder that I created in the root (not shared) google drive (I named it backup)..
function moveFiles(sourceFileId, targetFolderId) {
var file = DriveApp.getFileById(sourceFileId);
file.getParents().next().removeFile(file);
DriveApp.getFolderById(targetFolderId).addFile(file);
}
Upvotes: 1
Views: 4497
Reputation: 3340
To check the created files after the last time you ran the script you can use the property service [1] to save the date milliseconds and compare it with the file created date, which you can get using getCreated()
function to each file [2]. To copy the file with a custom name use makeCopy
function [3]. To completely remove the file (not trash bin) use the delete request [4] with Drive Advance Service (you have to activate it) [5].
function moveFiles(sourceDriveId, targetFolderId) {
var scriptProperties = PropertiesService.getScriptProperties();
var lastUpdate = scriptProperties.getProperty('lastUpdate');
if(lastUpdate == null) {
scriptProperties.setProperty('lastUpdate', new Date().getTime());
return;
}
var targetFolder = DriveApp.getFolderById(targetFolderId);
var sourceDrive = DriveApp.getFolderById(sourceDriveId);
var files = sourceDrive.getFiles();
while(files.hasNext()){
var file = files.next();
if(file.getDateCreated().getTime() > lastUpdate) {
file.makeCopy(file.getName(), targetFolder);
Drive.Files.remove(file.getId(), {supportsAllDrives: true});
}
}
scriptProperties.setProperty('lastUpdate', new Date().getTime());
}
function test() {
moveFiles("[SOURCE-DRIVE-ID]", "[TARGET-FOLDER-ID]");
}
[1] https://developers.google.com/apps-script/reference/properties/properties
[2] https://developers.google.com/apps-script/reference/drive/file#getdatecreated
[3] https://developers.google.com/apps-script/reference/drive/file#makecopyname,-destination
[4] https://developers.google.com/drive/api/v3/reference/files/delete
[5] https://developers.google.com/apps-script/advanced/drive
Upvotes: 1