Search code examples
filegoogle-apps-scriptmovegoogle-drive-shared-drive

How to move files in Google Drive automatically with Google Script, based on partial file name?


I'm rather new to Google Scripts. We are wanting to make all files uploaded to a single folder in Google Drive be automatically moved to other folders, based on part of their file name. 3 example files: APX PMT 05.02.2019, ALT PMT 05.03.2019, BEA PMT 05.04.2019 We want these files to be moved to their destination folders based on the first 3 letters of their file name. APX PMT 05.02.2019 gets moved to the APX folder, ALT PMT 05.03.2019 gets moved to the ALT folder, ect.

Do not have code samples as I'm extremely new to this. Move files automatically from one folder to another in Google Drive is a good start on me learning this, but still unsure how to make it move file based on only part of the file name.

Results: Wanting people to be able to upload files to a single destination, and the code auto moves them to their proper folders.

Test Code version 2.0 . Works as below if I remove the spaces between the 2 character sets (change BEA RFT to BEARFT or BEA_RFT) , as our workplace would like them sorted by the first 7 characters in the file name now. How can i make it work when there is a space in the characters?:

function moveFiles() {
  var dfldrs=['BEA RFT', 'BEA ADJ', 'BEA PMT', 'BEA CHG'];//Seven letter prefixes
  var ofObj={BEA RFT:'ID',BEA ADJ:'ID',BEA PMT:'ID',BEA CHG:'ID'};//distribution folder ids
  var upldFldr=DriveApp.getFolderById('ID');
  var files=upldFldr.getFiles();
  while(files.hasNext()) {
    var file=files.next();
    var key=file.getName().slice(0,7);
    var index=dfldrs.indexOf(key);
    if(index>-1) {
      Drive.Files.update({"parents": [{'id': ofObj[key]}]}, file.getId());  
    }
  }
}

Solution

  • Moving Files

    Please, Read these instructions before running script

    1. You need to provide the three letter prefixes
    2. You need to provide the distribution folder ids associated with each prefix
    3. You need to provide the upload folder id
    4. You need to run this program from your upload file script or provide an alternate trigger function as you desire.
    5. You need to enable Advance Drive API version 2

    The Code

    function moveFiles() {
      var dfldrs=['APX','ALT','BEA'];//Three letter prefixes
      var ofObj={APX:'APX id',ALT:'ALT id',BEA:'BEA id'};//distribution folder ids
      var upldFldr=DriveApp.getFolderById('folderid');
      var files=upldFldr.getFiles();
      while(files.hasNext()) {
        var file=files.next();
        var key=file.getName().slice(0,3);
        var index=dfldrs.indexOf(key);
        if(index>-1) {
          Drive.Files.update({"parents": [{"id": ofObj[key]}]}, file.getId());  
        }
      }
    }
    

    Drive API Reference