How can I retrieve the parent folder name from a Google Docs file using its ID?

I need help with a Google Apps Script task. I have a spreadsheet with Google Docs URLs in one column, and I want to automatically fill another column with the folder names where these documents are stored.

Specifically, I need to:

  • Extract the folder name (just the immediate parent folder, not the full path)
  • Use either the document ID or complete URL as input
  • Update a column named “Folder” in my spreadsheet
  • Process all rows in the sheet automatically

I’m pretty new to this and not sure where to start. Has anyone done something similar before? Any code examples or guidance would be really helpful.

The goal is to have this run through all the document links in my sheet and populate the folder information automatically.

Been wrestling with similar batch processing lately. The DriveApp approach works well, but watch out for URL parsing - Google Docs URLs come in different formats depending on how they’re shared. Just grab everything between ‘/d/’ and ‘/edit’ and you’ll catch most cases. Heads up - if your docs are in shared drives instead of regular folders, you’ll need DriveApp.getFileById(id).getParents(). That returns an iterator, not a folder object (learned that one the hard way). Cache your results if you can since folder structures don’t change much. No point hammering the API every run. For big datasets, I process 50-100 rows at a time with short pauses between batches. Keeps timeouts away.

The Problem:

Estás intentando obtener el nombre de la carpeta principal donde se almacena un documento de Google Docs usando solo la URL del documento y Google Apps Script. Tu script actual podría estar enfrentando problemas para extraer correctamente el ID del documento de la URL o para interactuar con la API de Google Drive para obtener la información de la carpeta.

:gear: Step-by-Step Guide:

  1. Extrae el ID del documento de la URL: La URL de un documento de Google Docs generalmente tiene este formato: https://docs.google.com/document/d/{documentId}/edit. Necesitas extraer el {documentId}, que es una cadena única que identifica el documento. Puedes usar una expresión regular para lograrlo.

    function getDocumentId(url) {
      const regex = /\/d\/([a-zA-Z0-9-_]+)\//;
      const match = url.match(regex);
      return match ? match[1] : null;
    }
    
  2. Obtén el objeto File de Google Drive: Usa el ID del documento extraído en el paso anterior para obtener el objeto File correspondiente de Google Drive. Esto te permite acceder a la información del archivo, incluyendo su carpeta principal.

    function getParentFolderName(documentId) {
      try {
        const file = DriveApp.getFileById(documentId);
        const parent = file.getParents().next(); //Obtiene la primera carpeta padre.  Podría haber más si el documento está en múltiples carpetas.
        return parent ? parent.getName() : "Raíz de Drive"; //Manejo para archivos en la raíz de Drive.
      } catch (error) {
        Logger.log("Error al obtener la carpeta principal: " + error);
        return null; //O un valor que indique fallo
      }
    }
    
  3. Integra las funciones en tu script principal: Combina las dos funciones anteriores en tu script para procesar cada URL de tu hoja de cálculo. Asume que la columna con las URLs se llama “URL” y la columna donde deseas escribir el nombre de la carpeta se llama “Carpeta”.

    function obtenerNombresCarpetas() {
      const ss = SpreadsheetApp.getActiveSpreadsheet();
      const sheet = ss.getSheetByName("TuNombreDeHoja"); // Reemplaza "TuNombreDeHoja"
      const urls = sheet.getRange("URL1:URL").getValues().flat(); //Suponiendo que las URLs están desde URL1 hasta la última fila.
      const folderNames = [];
    
      for (let i = 0; i < urls.length; i++) {
        const url = urls[i];
        const documentId = getDocumentId(url);
        if (documentId) {
          const folderName = getParentFolderName(documentId);
          folderNames.push([folderName]);
        } else {
          folderNames.push(["ID no encontrado"]);
        }
      }
    
      sheet.getRange("Carpeta1:Carpeta").setValues(folderNames); //Suponiendo que los nombres de carpeta van desde Carpeta1.
    }
    
  4. Manejo de errores y casos especiales: Asegúrate de incluir manejo de errores para las URLs inválidas, los IDs de documento no encontrados, o los casos donde un documento no tenga una carpeta padre (ej., está en la raíz de Drive). El código incluye ejemplos básicos de manejo de errores, pero puede que necesites añadir más dependiendo de los errores que puedas encontrar.

  5. Prueba con un pequeño conjunto de datos: Antes de aplicar el script a toda tu hoja de cálculo, pruébalo con un pequeño conjunto de datos para asegurarte de que funciona correctamente. Esto te permitirá identificar y corregir cualquier error antes de procesar una gran cantidad de datos.

:mag: Common Pitfalls & What to Check Next:

  • Permisos de Google Drive: Asegúrate de que tu script de Google Apps tenga los permisos necesarios para acceder a Google Drive.
  • Formato de las URLs: Verifica que el formato de las URLs en tu hoja de cálculo sea correcto. La expresión regular podría necesitar ajustes si las URLs tienen un formato diferente.
  • Límites de la API: Google Drive API tiene límites de solicitudes por segundo y por día. Si estás procesando una gran cantidad de documentos, es posible que necesites agregar pausas entre las llamadas a la API para evitar superar estos límites.
  • Nombres de Hoja: Verifica que los nombres de tus hojas (“TuNombreDeHoja”, en el ejemplo) sean los correctos.

:speech_balloon: Still running into issues? Share your (sanitized) config files, the exact command you ran, and any other relevant details. The community is here to help!

Sounds like you’re stuck with repetitive data extraction. I’ve automated this stuff tons of times - manual scripting becomes a nightmare quick.

That approach works but you’ll waste hours on edge cases and rate limits. Skip the custom Google Apps Script and use a proper integration platform instead.

Just set up a workflow that reads your spreadsheet, grabs document IDs from URLs, hits the Google Drive API for parent folder names, then dumps everything back to your sheet. Runs automatically without touching code.

Built something similar last month for our document audit. Takes minutes to configure and handles errors automatically. No more API quota headaches or folder hierarchy problems.

You can extend it later for full folder paths or other file types. Way more reliable than maintaining custom scripts.

Check out https://latenode.com for this kind of automation.

Quick tip - check for files in your root drive without parent folders first, or you’ll get errors. Also, shared docs won’t return folder names without proper permissions, so wrap getName() in a try-catch to prevent crashes.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.