P.J
P.J

Reputation: 85

Data movement of wrong files

I wrote a function to move files from a folder to another folder. it works but the issue that when opening the destination folder I see my google script and some other documents that aren't in the source folder.

here is the code


function moveFiles() {
var currentMonth = Utilities.formatDate(new Date(), "GMT+6", "MMMM");
const source_folder = DriveApp.getFolderById('XXXXXXX');
const files = source_folder.getFiles();
const dest_folder = DriveApp.getFolderById('XXXXXX').createFolder(currentMonth + " test text");
while (files.hasNext()) {
const file = files.next();
dest_folder.addFile(file);
source_folder.removeFile(file);
}
}



thanks in advance

Upvotes: 0

Views: 43

Answers (1)

Tanaike
Tanaike

Reputation: 201603

I believe your goal as follows.

  • You want to move the files to the created folder using Google Apps Script.

  • From the following situation,

    it works but the issue that when opening the destination folder I see my google script and some other documents that aren't in the source folder.

    • I though that you might want to move the files of specific mimeType to the folder.
  • In the current stage, I think that moveTo(destination) of Class File can be used for moving the files to the folder.

Modified script 1:

In this modification, the files are retrieved using getFilesByType.

function moveFiles() {
  var currentMonth = Utilities.formatDate(new Date(), "GMT+6", "MMMM");
  const source_folder = DriveApp.getFolderById('XXXXXXX');
  const files = source_folder.getFilesByType(MimeType.GOOGLE_SHEETS);
  const dest_folder = DriveApp.getFolderById('XXXXXXX').createFolder(currentMonth + " test text");
  while (files.hasNext()) {
    files.next().moveTo(dest_folder);
  }
}
  • In this modified script, Google Spreadsheet files are moved.
  • When you want to modify the mimeType, please modify MimeType.GOOGLE_SHEETS for your situation.

Modified script 2:

In this modification, the files are retrieved using getFiles and the mimeTypes are checked in the loop.

function moveFiles() {
  var currentMonth = Utilities.formatDate(new Date(), "GMT+6", "MMMM");
  const source_folder = DriveApp.getFolderById('XXXXXXX');
  const files = source_folder.getFiles();
  const dest_folder = DriveApp.getFolderById('XXXXXXX').createFolder(currentMonth + " test text");
  const exclusiveMimeTypes = [MimeType.GOOGLE_APPS_SCRIPT, MimeType.GOOGLE_DOCS];
  while (files.hasNext()) {
    const file = files.next();
    if (!exclusiveMimeTypes.includes(file.getMimeType())) {
      file.moveTo(dest_folder);
    }
  }
}
  • In this sample script, from when opening the destination folder I see my google script and some other documents that aren't in the source folder, the files except for the Google Apps Script files and Google Document files are moved.
  • If you want to add more exclusive mimeTypes, please modify above script.

References:

Upvotes: 1

Related Questions