Google Apps Scripts: Create a Folder in the Root Drive

Walden Systems Geeks Corner News Google Apps Scripts: Create a Folder in the Root Drive Rutherford  NJ New Jersey NYC New York City North Bergen County

Working with google sheets one quickly realizes there are many good reasons to automate many tasks. Even simple tasks, like creating folders or resizing columns and rows can take 4 to 5 mouse clicks plus a couple of keyboard clicks, to get accomplished. This is more than tedious, annoying and time consuming. In this blog we will go over a simple yet very useful function to automate the task of creating folder(s).

I often work with data sets that are populated from a database or another spreadsheet to analyze big chunks of data. Once I have my spreadsheet built out from my dataset, I automate many of the tasks from within my Google Apps Script code base. In this blog I will automate the creation of folders in my Google Drive root folder.


Here a nifty function that will create a new folder under my root drive comes in handy, ‘createFolder()’. The function ‘createFolder()’ belongs to the Apps Script Class, called ‘DriveApp’. The Class ‘DriveApp’ handles most of the services allowing scripts to create, find, and modify files and folders in Google Drive.

Let's start with our function signature that takes one parameters: ‘folderName’.


function createNewFolder(folderName)
Second function, is a helper method to create a folder name that will be easily recognized under the root folder of Google Drive.

function crtFolderName()
Putting it all together:

function crtFolderName() {
  var timeStamp;
  var dateTimeAsString;
  var newFolderName; 
  
  timeStamp = new Date();
  dateTimeAsString = timeStamp.toString().slice(0,15);
  dateTimeAsString = dateTimeAsString.replace(/s+/g, '');
  newFolderName = 'NewFolder-' + dateTimeAsString;

  return(newFolderName);
};

function createNewFolder(folderName) {
  var folder = DriveApp.createFolder(folderName);
  return(folder);
};

function myMainBlog() {
  var newFolderName = crtFolderName();
  Logger.log(newFolderName);
  var folder = createNewFolder(newFolderName);
  Logger.log(folder);
};