Search code examples
google-apps-scriptgoogle-drive-apigoogle-drive-shared-drive

Google Apps Script moving file to Team Drive folder


Background: At the core of the issue is I have an Alteryx job dropping files into my google drive. These files need, in actuality, in a Team Drive folder. Try as I might, nowhere have I found a way for Alteryx to do this. So hence the need for this script.

Actual problem: So here is the criteria: I have the files being created with the same naming convention with only the date changing. I need these files to go from my drive to a team drive where they are eventually worked on. Using the resources already here on stack I found wonderful solutions here: 1 and here 2 that I was able to cobble together a working script.

Understand I am a marginally functional python programmer for data analytics. So my JS and Google scripting are rudimentary at best. The first time I tested the script, it worked. Wonderfully, right up until it didn't. It moved my first file with no problem. I then created a few copies of that same file in the drive to see how it handled multiple. I now get an error:

Exception: No item with the given ID could be found, or you do not have permission to access it. (line 15, file "CodeA1")

Here is my code:

function SearchFiles() {
  //searches based on naming criteria 
  var searchFor ='title contains "Reference Data Performance"'; //test file
  var names =[];
  var fileIds=[];
  var files = DriveApp.searchFiles(searchFor);
  while (files.hasNext()) {
    var file = files.next();
    var fileId = file.getId();// To get FileId of the file
    fileIds.push(fileId);
    var name = file.getName();
    names.push(name); 

  }
var file = DriveApp.getFileById(fileIds);
supportsTeamDrives: true;
        supportTeamDrives: true;
        var targetFolder = DriveApp.getFolderById('TEAMDriveID');
        targetFolder.addFile(file);

}

Solution

  • Exception: No item with the given ID could be found, or you do not have permission to access it.

    This error occurs most often if either

    • The TeamDriveId is not correct
    • The account from which you run the script is not member of the team drive

    Also note:

    supportsTeamDrives: true; supportTeamDrives: true;

    are parameters for the Drive API, not to be confused with DriveApp