0

I'm horrible at coding so I'm sure this will need some work.

My Problem: My company does work for a lot of other companies (example Drive hierarchy photo attached). Each company we work with gets their own folder that is nested under the folder 'Shirts for other companies". We put all their assets into these folders (logos, mocks, quotes).

We want to build a script that will look into the individual company folders and take any file that starts with the word Mock and automatically copy it and put it into the database folder found in the picture below.

Here is the script have so far. but I'm having trouble getting into the subfolders (ford tshirts and designs). Not only that, but if it runs everyday the script will keep duplicating the files it has duplicated in the past which I want to avoid.

Script:

Function getTheFiles() {

 var dApp = DriveApp;
 var folderIter = dApp.getFolderByName("Shirts for other companies");
 var folder = folderIter.next();
 var filesIter = folder.getFiles();
 var dataBase = folder.getFoldersByName("database1").next();

 var i = 1;

 while(filesIter.hasNext()) {
  var file = filesIter.next();
  var filename = file.getName();
  
  if(filename = "mocking") {
   file.makeCopy(dataBase);
  }

  logger.log(filename);
  i++;
 }

Rubén
  • 34,714
  • 9
  • 70
  • 166
Matt k
  • 1
  • 2
  • You'll probably want to use something like [this](https://stackoverflow.com/a/55248127/7215091) to recurse through the folders – Cooper Jan 24 '20 at 20:05
  • Alright i will look into that, might be beyond my level though. – Matt k Jan 24 '20 at 20:15
  • It's harder to think than it is to write. – Cooper Jan 24 '20 at 20:16
  • You don't really need to copy the files and move them into another folder all you really need to do to access them to store their urls in a spreadsheet in some logical fashion and click on them when you want to open them. – Cooper Jan 24 '20 at 21:50

2 Answers2

1

If I understood you correctly, you want to:

  • Copy all files from the different subfolders inside a folder called "Shirts for other companies", that start with the word mock, to the Database folder (which is also inside the main folder).
  • Avoid files getting copied many times.

If that's the case, you could do the following:

  • Search for all files in each subfolder of the main folder that start with mock, excluding the files inside Database folder. For this, you iterate through all files in each subfolder (after checking the subfolder is not named Database folder. For each file, you check that the name start with mock, using the method substring.
  • To keep track of which files are copied, and so avoid making duplicates, you can use PropertiesService, which can store key-value pairs. The id of every copied file is copied to the script property, and then, the next time the script runs, it checks whether the id is in the property. If that's the case, the file doesn't get copied again. One thing to notice is that script properties can only store strings, so that arrays have to be converted to a string every time we want to store a new id (via toString, and back to an array, via split.

The function below does all these things (check inline comments for more details):

function copyFiles() {
  var mainFolder = DriveApp.getFoldersByName("Shirts for other companies").next();
  var folders = mainFolder.getFolders(); // Get folder iterator from main folder 
  var databaseFolderName = "Database folder"; // You database folder name
  var databaseFolder = mainFolder.getFoldersByName(databaseFolderName).next(); // Get databse folder
  var idsArray = []; // Array to store the ids of the copied files
  while (folders.hasNext()) { // Iterate through each folder in the main folder
    var folder = folders.next();
    if (folder.getName() !== databaseFolderName) { // Check current folder is not the database folder
      var files = folder.getFiles();
      while (files.hasNext()) { // Iterate through each file in each subfolder
        var file = files.next();
        if (file.getName().substring(0, 4).toLowerCase() === "mock") { // Check that file name starts with "mock"
          // Get ids of the files that were copied in previous executions:
          var key = "copied-ids";
          var scriptProperties = PropertiesService.getScriptProperties();
          var ids = scriptProperties.getProperty(key);
          if (ids) idsArray = ids.split(",");
          else ids = "";
          // Get current file id:
          var id = file.getId();
          // Check that current file id is not in properties (not copied before):
          if (idsArray.indexOf(id) === -1) {
            file.makeCopy(databaseFolder); // Copy file to database folder
            idsArray.push(id); // Add file id to the array of copied files
          }
          ids = idsArray.toString();
          scriptProperties.setProperty(key, ids);
        }
      }
    }
  }
}

Reference:

I hope this is of any help.

Iamblichus
  • 18,540
  • 2
  • 11
  • 27
  • I apologize about any delay. Don't sign on too often. I really appreciate the help! I will work on this today. hopefully I can figure it out. Either way I truly appreciate the help. – Matt k Feb 06 '20 at 22:33
0

This function would search your entire Google Drive for files starting the the letter Mock and put Name, url, id, type (folder or file) into the active spreadsheet and tab named MoclList;

function getAllMocks() {
  var ss=SpreadsheetApp.getActive();
  var sh1=ss.getSheetByName('MocksList');
  sh1.clearContents();
  sh1.appendRow(['Name','Url','Id','Type']);
  getFnF();
  SpreadsheetApp.getUi().alert('Process Complete')
}

var level=0;
function getFnF(folder) {
  var folder= folder || DriveApp.getRootFolder();
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName('MocksList');
  var files=folder.getFiles();
  while(files.hasNext()) {
    var file=files.next();
    if(file.getName().toLowerCase().slice(0,4)=='mock') {
      var firg=sh.getRange(sh.getLastRow() + 1,level + 1);
      firg.setValue(file.getName());
      firg.offset(0,1).setValue(Utilities.formatString('=HYPERLINK("%s","%s")',file.getUrl(),'FILE: ' + file.getName()));
      firg.offset(0,2).setValue(file.getId());
      firg.offset(0,3).setValue('File');
    }
  }
  var subfolders=folder.getFolders() 
  while(subfolders.hasNext()) {
    var subfolder=subfolders.next();
    var forg=sh.getRange(sh.getLastRow() + 1,level + 1);
    forg.setValue(subfolder.getName());
    forg.offset(0,1).setValue(Utilities.formatString('=HYPERLINK("%s","%s")',subfolder.getUrl(),'FOLDER: ' + subfolder.getName()));
    forg.offset(0,2).setValue(subfolder.getId());
    forg.offsert(0,3).setValue('Folder');
    //level++;
    getFnF(subfolder);
  }
  //level--;
}
Cooper
  • 59,616
  • 6
  • 23
  • 54