Home > database >  Google Apps Script Filter Output Before Moving
Google Apps Script Filter Output Before Moving

Time:07-09

Good Morning All,

I should filter the output by the name (must contain a specific word) of the file before it is moved... How can I do this? With this script it moves all the files it finds indiscriminately, but that is not what I want

function moveFiles(sourceFileId, targetFolderId) {
  var file = DriveApp.getFileById(sourceFileId);
  var folder = DriveApp.getFolderById(targetFolderId);
  file.moveTo(folder);
}

function searchDrive() {
  var inputMe = 'MYDRIVEID';
  var inputFolder = DriveApp.getFolderById(inputMe);
  var files = inputFolder.getFiles();
  while (files.hasNext()) {
    var destinationFolderId = "MYDRIVEID";
    var file = files.next();
    var moveMe = file.getId();
    var moveMeName = file.getName();
    Logger.log(moveMeName);
    moveFiles(moveMe,destinationFolderId);
  }
}

CodePudding user response:

In your situation, how about the following modification?

Modified script:

In this modification, your searchDrive is modified. Please set the filter texts to filterTexts.

function searchDrive() {
  var filterTexts = ["sample1", "sample2",,,]; // Please set the filter text you want to use.

  var inputMe = 'MYDRIVEID';
  var inputFolder = DriveApp.getFolderById(inputMe);
  var files = inputFolder.getFiles();
  while (files.hasNext()) {
    var destinationFolderId = "MYDRIVEID";
    var file = files.next();
    var moveMe = file.getId();
    var moveMeName = file.getName();
    if (!filterTexts.some(e => moveMeName.toUpperCase().includes(e.toUpperCase()))) {
      moveFiles(moveMe, destinationFolderId);
    }
  }
}
  • When this script is run, the files with the filename which doesn't include the texts of filterTexts are moved.
  • If you want to distinguish the uppercase and lowercase of the filename, please remove toUpperCase().

Reference:

CodePudding user response:

As a quick fix you can just replace:

moveFiles(moveMe,destinationFolderId);

with:

if (moveMeName.contains('specific word')) moveFiles(moveMe,destinationFolderId);

or (for case insensitive mode):

if (moveMeName.toLowerCase().contains('specific word')) moveFiles(moveMe,destinationFolderId);
  • Related