2

Google app script newbie here. I found this code which helps create folders in my personal Google drive with using inputs from Google sheet (credit: Google Sheet Community on Youtube). However, when I tried to recreate this app in a shared Google drive, it failed to run and kept creating folders in my personal drive instead. Is there anything I can change about the code to make it work in the shared drive environment instead of my own?

Thanks a lot!

  var ui = SpreadsheetApp.getUi();
// Or DocumentApp or FormApp. 
  ui.createMenu('GDrive')
    .addItem('Create new Folders', 'crtGdriveFolder')
    .addToUi(); }


function crtGdriveFolder() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2; // First row of data to process
  var numRows = sheet.getLastRow(); // Number of rows to process
  var maxRows = Math.min(numRows,20); //Limit the number of rows to prevent enormous number of folder creations
  var folderid = sheet.getRange("C2").getValue();
  var root = sheet.getRange("D2").getValue();
  var dataRange = sheet.getRange(startRow, 1, maxRows, 2); //startRow, startCol, endRow, endCol
  var data = dataRange.getValues();
  var folderIterator = DriveApp.getFoldersByName(folderid); //get the file iterator


if(!folderIterator.hasNext()) { SpreadsheetApp.getActiveSpreadsheet().toast('Folder not found!');
return; }


var parentFolder = folderIterator.next();


if(folderIterator.hasNext()) {
SpreadsheetApp.getActiveSpreadsheet().toast('Folder has a non-unique name!');
return; }


for (i in data) {
var row = data[i];
var name = row[0]; // column A
var desc = row[1]; // column B


if(root == "N" && name != "") {
var idNewFolder = parentFolder.createFolder(name).setDescription(desc).getId(); Utilities.sleep(100);
var newFolder = DriveApp.getFolderById(idNewFolder);


  } if(root == "Y" && name != "") {
      var idNewFolder = DriveApp.createFolder(name).setDescription(desc).getId();
      Utilities.sleep(100);
      var newFolder = DriveApp.getFolderById(idNewFolder);

      }

}
}

Rubén
  • 34,714
  • 9
  • 70
  • 166
ssh
  • 23
  • 3

1 Answers1

4

DriveApp creates folders by default in your own Drive

  • If you want to create a folder on a shared Drive instead, you need to use the the Advanced Drive Service based on the Drive API
  • Make sure to enable the advanced service before using
  • Use the advanced option {supportsAllDrives : true}
  • Specify the id of the shared Drive as parents

A sample how to create a folder on the shared drive based on your code:

} if(root == "Y" && name != "") {
  var optionalArgs={supportsAllDrives: true};
  var resource = {
    title: name,
    description: desc,
    mimeType: "application/vnd.google-apps.folder",
    parents:[{
      "id": "ID OF SHARED DRIVE"
    }]
  }  
  var idNewFolder = Drive.Files.insert(resource, null, optionalArgs).id;
  Utilities.sleep(100);
  var newFolder = DriveApp.getFolderById(idNewFolder);
}
ziganotschka
  • 25,866
  • 2
  • 16
  • 33