1

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);
 }
}

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

thank you, it really helps. can i ask something? how to use folder name instead of folder id? i know need to use getfolderbyname, but how immplement it? sorry for the noob question
actually i want to copy file and i removed removeFile(file). and the copy worked successfully. but when i tried to delete the file at the original folder, the copied file at the other folder also deleted. how to avoid this sir? tqvm

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.