Home > OS >  GAS - Apps Script retrieve last created folder Id
GAS - Apps Script retrieve last created folder Id

Time:05-28

I am doing a apps script app that will store some data inside folders that I pretend to create depending on current date, i.e, the script will look if inside a parent folder with known id is a folder named with current year, if there is not then will create the folder, then will check which month is it and create month folder inside the year folder, last it will create a custom folder with custom data inside month folder. The problem is that I just could create the year folder with the following code:

function createFolder(date){

  var year = date.substring(6,10);
  var month = meses[date.substring(3,5)];

  var yearFolder

  var parentFolder = DriveApp.getFolderById(parentFolderId);
  
  // Gets FolderIterator for yearFolder
  yearFolders = parentFolder.getFoldersByName(year);
  /* Checks if FolderIterator has Folders with given name
  Assuming there's only a yearFolder with given name... */ 
  while (yearFolders.hasNext()) {
    yearFolder = yearFolders.next();
  }
  if (!yearFolder) {parentFolder.createFolder(year);
                     
                   }
}

i want to use the same code to create the month and custom folders but the problem is that i cant retrieve the id of the created year folder and then the month one. How can i do it?

CodePudding user response:

To get the id of the "year" folder replace

if (!yearFolder) {parentFolder.createFolder(year);
                     
                   }

by

if (!yearFolder) {
yearFolder = parentFolder.createFolder(year);
                     
                   } 
const yearFolderId = yearFolder.getId();

CodePudding user response:

If my understanding with your goal is correct, you dont need to get the folder id, just use the newly created yearFolder. Just make sure to assign it to the yearFolder variable to store that folder object if it doesn't exist.

Unless your goal is to store those IDs, this approach should also work.

Snippet:

yearFolders = parentFolder.getFoldersByName(year);

while (yearFolders.hasNext()) 
  yearFolder = yearFolders.next();

if (!yearFolder)
  // Store returned folder object into yearFolder if it doesn't exist 
  // Then use it for the month counterpart
  yearFolder = parentFolder.createFolder(year);
                     
// Repeat above code but now uses yearFolder as parentFolder
monthFolders = yearFolder.getFoldersByName(month);

while (monthFolders.hasNext()) 
  monthFolder = monthFolders.next();

if (!monthFolder)
  monthFolder = yearFolder.createFolder(month);

// Then create custom folder in monthFolder, then following the file
customFolder = monthFolder.createFolder('customFolder');
customFolder.createFile('customData', customData)
  • Related