Amin Harith
Amin Harith

Reputation: 11

Move Files in google script

i use the function MoveFiles() to copy file into other folder. But when i ran it, i try to delete the file in the original folder. After deleted it, i saw that the file that i moved also deleted. How to make the file that i moved not be deleted too? Tqvm

function MoveFiles() {
var SourceFolder = DriveApp.getFolderById('1WIZxuF_r9I-510Kfw9N0AImcS1Uf63dC');
var SourceFiles = DriveApp.getFolderById('1QfFl5JIfOYaTXZyFpuBNSMzBdBrXLll9').getFiles();
 var DestFolder = DriveApp.getFolderById('1_03PnkJlt6mTo5bAExUMOdZVVkzMAUsA');

while (SourceFiles.hasNext()) {
 var file = SourceFiles.next();
 DestFolder.addFile(file);
 SourceFolder.removeFile(file);
 }
}

Upvotes: 1

Views: 1179

Answers (1)

Mr.Rebot
Mr.Rebot

Reputation: 6791

Try switching the code line for delete and add. According to this related SO post:

I've found that I needed to reverse the last two lines (so the removeFile is done first) otherwise the removeFile actually just removes it from the folder it was just added to and not from the original parent.

I've tested it and actually get the correct result, here is my code snippet:

function myFunction() {
  var folder = DriveApp.getFolderById('sourceID');
  var destinationFolder = "destinationID";
  var contents = folder.getFiles();

  while (contents.hasNext()){
    var file = contents.next();
    moveFiles(file.getId(),destinationFolder);
  }


}

function moveFiles(sourceFileId, targetFolderId) {
  var file = DriveApp.getFileById(sourceFileId);
  file.getParents().next().removeFile(file);
  DriveApp.getFolderById(targetFolderId).addFile(file);
}

Hope this helps.

Upvotes: 1

Related Questions