Specific Folder - search for subfolder and contents using GAS

727 views
Skip to first unread message

JMR...

unread,
Apr 23, 2024, 5:05:27 PM4/23/24
to Google Apps Script Community
Hi, I am wondering if it is possible to use Google Script to search for a subfolder in a specific folder?

For example: 3.1 subfolder (Folder to search)
- Specific folderId = 123456789abc
- Go the drive specific folderId and locate if any of the subfolders starts with "3."
- If there is a match, then start the searching that subfolder if it contains "3.1 subfolder" and log if there are any contents.

I have used the searchFolders in the past but I am not sure it is possible using the scenario above.

TIA for any input!
J-

Laurie Nason

unread,
Apr 24, 2024, 12:54:14 AM4/24/24
to google-apps-sc...@googlegroups.com

Hi,
Asking Gemini for this, here's what I got - it looks pretty much what you need - or at the very least, it will provide a starting point for you.

function listSubfolderContents() {
  // Replace 'FOLDER_ID' with the actual ID of the folder you want to search
  const folderId = 'FOLDER_ID';
 
  // Get the folder object by ID
  const folder = DriveApp.getFolderById(folderId);
 
  // Initialize an empty array to store subfolder names and contents
  const subfolderData = [];
 
  // Get all subfolders within the main folder
  const subfolders = folder.getSubfolders();
 
  // Loop through each subfolder
  while (subfolders.hasNext()) {
    const subfolder = subfolders.next();
   
    // Check if subfolder name starts with "3."
    if (subfolder.getName().startsWith("3.")) {
      const subfolderName = subfolder.getName();
     
      // Get all files within the subfolder
      const files = subfolder.getFiles();
      const fileNames = [];
     
      // Loop through each file and collect names
      while (files.hasNext()) {
        const file = files.next();
        fileNames.push(file.getName());
      }
     
      // Add subfolder name and file list to the data array
      subfolderData.push({ name: subfolderName, files: fileNames });
    }
  }
 
  // Log the subfolder data to the console (optional)
  // Logger.log(subfolderData);
 
  // You can use the subfolderData array for further processing
  // (e.g., display in a spreadsheet, send an email notification)
 
  return subfolderData;
}

Explanation:

  1. Replace 'FOLDER_ID': Update the script with the actual ID of the folder you want to search. You can find the folder ID in the URL when you open the folder in your Drive.
  2. Get Folder Object: The script retrieves the folder object using DriveApp.getFolderById(folderId).
  3. Iterate Subfolders: It loops through all subfolders within the main folder using folder.getSubfolders().
  4. Check Subfolder Name: Inside the loop, it checks if the subfolder name starts with "3." using startsWith("3.").
  5. Collect File Names: If the name matches, it retrieves all files within the subfolder using subfolder.getFiles(). Then, it loops through each file and collects the names into an array called fileNames.
  6. Store Subfolder Data: Finally, it creates an object with the subfolder name (name) and the list of files (files) and pushes this object into the subfolderData array.
  7. Return Data (Optional): The script currently logs the subfolderData array to the console for debugging purposes (commented out). You can uncomment this line to view the results in the script editor's log. The return statement allows you to use the subfolderData array for further processing in your script, such as populating a spreadsheet or sending an email notification.

Note:

  • This script retrieves only the names of the files within the subfolders. You can modify it to access additional file properties if needed.
  • Remember to save the script in the Script Editor and run the listSubfolderContents function.


--
You received this message because you are subscribed to the Google Groups "Google Apps Script Community" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-apps-script-c...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/google-apps-script-community/59f74ab8-25f9-46e0-82a7-21a483d60a8bn%40googlegroups.com.

Brian Pugh

unread,
Apr 24, 2024, 9:33:53 AM4/24/24
to google-apps-sc...@googlegroups.com
Love the idea. However, getting this error: TypeError: folder.getSubfolders is not a function


















Brian Pugh, IT/Educational Technologies



Associated Hebrew Schools | Danilack Middle School

p: 416.494.7666, | e: bp...@ahschools.com

w: www.associatedhebrewschools.com

252 Finch Ave W., Toronto, ON M2R 1M9


facebook.png twitter.png instagram.png 


This email is confidential and is intended for the above-named recipient(s) only. If you are not the intended recipient, please delete this email from your system. Any unauthorized use or disclosure of this email is prohibited.




Laurie Nason

unread,
Apr 25, 2024, 12:32:08 AM4/25/24
to google-apps-sc...@googlegroups.com
Yeah - that's what I get for trusting AI.... 
had to tweak it a bit  but here's one that worked for me...
function listSubfolderContents() {
// Replace 'FOLDER_ID' with the actual ID of the folder you want to search
folderId = 'YOUR_FOLDER_ID';
// Get the folder object by ID
let folder = DriveApp.getFolderById(folderId);
// Initialize an empty array to store subfolder names and contents
let subfolderData = [];
// Get all subfolders within the main folder
let subfolders = folder.getFolders();
let sub=subfolders.hasNext();
// Loop through each subfolder
while (subfolders.hasNext()) {
let subfolder = subfolders.next();
// Check if subfolder name starts with "3."
if (subfolder.getName().startsWith('3.')) {
let subfolderName = subfolder.getName();
// Get all files within the subfolder
let files = subfolder.getFiles();
let fileNames = [];
// Loop through each file and collect names
while (files.hasNext()) {
let file = files.next();
fileNames.push(file.getName());
}
// Add subfolder name and file list to the data array
subfolderData.push({ name: subfolderName, files: fileNames });
}
}
// Log the subfolder data to the console (optional)
// Logger.log(subfolderData);
// You can use the subfolderData array for further processing
// (e.g., display in a spreadsheet, send an email notification)
return subfolderData;
}
Laurie

Laurie Nason IT Systems Analyst

P: +966 (0) 12 808 6853 W: www.tks.kaust.edu.sa

The KAUST School, Thuwal, Saudi Arabia



JMR...

unread,
Apr 25, 2024, 1:40:52 AM4/25/24
to Google Apps Script Community
Thank you for your input. I will review and see if it works for the stuff I am working on.

JMR...

unread,
Apr 25, 2024, 2:05:11 AM4/25/24
to Google Apps Script Community
I do have a question about the line:

if (subfolder.getName().startsWith("3.")) {
const subfolderName = subfolder.getName();

What if I have a designated cell value for "Folder/File Search Name" and the value may change. Is there a way to call out this particular cell value (i.e.g., cell B1)? So, the "startsWith()" may change to a different number or may not any number to begin with. I want to get away from using too many if/else statement here but if that is my only choice, I'll do this route instead.
Reply all
Reply to author
Forward
0 new messages