-1

I was delighted to find Amit Agarwal's script in Moving Files In Google Drive Using Google Script, that allows one to move a file from one folder to another on Google Drive.

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

How could this be modified to select only files of a specific type, say PDFs?

Community
  • 1
  • 1
Brian
  • 11
  • 6

1 Answers1

3

You should check the MIME type of the file and then move the matching files. Here's a modified version of the original snippet.

function moveFiles(source, target) {
  var sourceFolder = DriveApp.getFolderById(source);
  var targetFolder = DriveApp.getFolderById(target)
  var files = sourceFolder.getFilesByType(MimeType.PDF);
  while (files.hasNext()) {
    var file = files.next();
    targetFolder.addFile(file);  
    file.getParents().next().removeFile(file);
  }
}
Community
  • 1
  • 1
Amit Agarwal
  • 10,910
  • 1
  • 32
  • 43
  • Amit, exactly what we need. You've saved me (and I think many others) a great deal manual moving of files. Thank you very much! – Brian Sep 19 '16 at 22:29
  • @Brian If you feel the code solved the issue, you may accept the answer. – Amit Agarwal Sep 20 '16 at 04:46
  • I apologize, Amit, for my delay. I wanted to do some additional testing. I also have a folder which contains several sub-folders, each which contains 2 pdf's. Can your script move all the pdf's in the sub-folders if I use the root folder as the sourceID? Thanks very much. – Brian Sep 20 '16 at 10:30
  • 1
    Rather than `"application/pdf"`, I recommend using the built-in enum [`MimeType`](https://developers.google.com/apps-script/reference/base/mime-type), because it supports auto-completion in the editor, reducing the possibility of a typo breaking your code. `var files = sourceFolder.getFilesByType(MimeType.PDF);` – Mogsdad Sep 23 '16 at 17:44