I need a reliable Google Sheets script that counts files in multiple Google Drive folders.
Requirements:
Goal:
I want a script that takes a folder link (or ID) and counts all items inside the specified subfolders. The count should stay updated as new files are added, and the script should handle future changes automatically.
Current Issue:
The script sometimes fails to read files — I can see files inside the folders, but the script returns a count of zero. I need the solution to be accurate and reliable.if it done one whole run than in second run it wont update that old data as folder file updated or removed.
Hi Mario Rossi — thanks for the detailed response. My requirement is slightly more specific based on my sheet structure.
Each row contains a main Google Drive folder link in column E.
Inside that folder there are multiple subfolders (e.g. Folder 1, Folder 2, Folder 3 … Folder 7, Others)
I need the script to:
• Recursively scan the main folder
• Count files inside each specific subfolder category
• Put counts in columns F onward (Folder 1 → Folder 7 → Others)
• If files are added later, counts should update correctly
• Ignore trashed files
• Ignore shortcuts (count actual files only)
• Count all file types
• Work in batches (50 rows per run)
• Automatically continue until complete
• Remove trigger when finished
• Log progress for troubleshooting
• Provide stable counts (currently they change each run)
• Allow periodic updates (e.g. hourly) so counts stay updated when files changeFolder classification logic:
• If file is inside subfolder named "Folder 1" → count in column F
• If inside "Folder 2" → column G
• … up to Folder 7 so onSheet name: use the existing sheet (first tab is fine)
Approximate size: around 8k–10k files total (may grow later).
Main requirement: counts must be consistent and reliable. Currently I get different values on each run, so stability is very important.
The sample sheet I shared reflects the structure I need.
Thanks — looking forward to the script.
Hi Sagar,
I implemented this using Google’s stable APIs directly, not Apps Script. So it is not limited by Apps Script execution time, trigger behavior, or quota constraints.
It can handle the workflow you described:
I also ran a working demo on your sheet structure. Please check this demo:
Demo sheet
If this is still useful for you, I can package it into a clean working version for your sheet.
Also, what would be a reasonable budget for you if this saves you from the current manual checking and unreliable counts?
--
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 visit https://groups.google.com/d/msgid/google-apps-script-community/CACrgDdqZzoeokCgcrF7y8E%3DSmGj8AEdh7ZP_1cV6MUT66gzGGg%40mail.gmail.com.
With kind regards,
Ben
Hi Ben,
Thanks for sharing your approach and the demo, it looks really solid.
Right now I’m trying to get this working reliably within Google Apps Script so everything stays simple and self-contained. Before I go down the route of a paid or external solution, I just want to understand a bit more.
Do you think the issues I’m seeing, like inconsistent counts, zero results, and rows not updating, can be fully fixed within Apps Script if done properly using the Drive API and pagination? Or did you run into limitations that made it unreliable in your case?
It would really help if you could share what didn’t work well with Apps Script in your experience, and what your solution does better in terms of accuracy, scalability, and maintenance.
At the moment I’m prioritizing a free Apps Script solution, and I’d only consider a paid setup if this genuinely can’t be made reliable.
That said, if you have a rough estimate for a basic packaged version without ongoing support, feel free to share.
Thanks again, appreciate your time.
Regards
Hi Mario,
Thanks — your proposed approach looks good and aligned with what I need. Please go ahead with the implementation using your default assumptions, with the following confirmations:
Configuration:
• Include Shared Drives: Yes
• Column mapping:
Folder 1 → F, Folder 2 → G, Folder 3 → H, Folder 4 → I, Folder 5 → J, Folder 6 → K, Folder 7 → L, Others → M
• Classification: Match “Folder X” anywhere in the path (case-insensitive)
• Files directly inside the main folder should count as “Others”
• Sheet structure: Header in row 1, data starting from row 2
• Add a last-run timestamp column for each row
File Handling Rules:
• Ignore trashed files
• Ignore shortcuts
• Count all file types
Reliability & Accuracy Requirements:
• The script must always produce deterministic counts (same result if no changes occurred)
• It should never return 0 unless the folder is actually empty
• Ensure no duplicate counting (use file ID deduplication)
• Handle pagination correctly to avoid missing files in large folders
• Fully overwrite previous results every run so additions/removals are reflected
Robustness Enhancements:
• Implement a retry mechanism in case Drive API pagination fails mid-run
• Maintain a checkpoint (e.g., last processed page token or folder) so partial runs can resume instead of restarting
• If a folder is invalid or inaccessible, log it clearly and skip it instead of failing the entire batch
Logging Requirements:
Please include clear logging for:
• Row number being processed
• Resolved folder ID
• Total files scanned
• Final counts per category
• Any errors or skipped cases
Performance & Execution:
• Batch size: 50 rows per run
• Use continuation triggers until processing is complete
• Automatically remove the trigger after full completion
• Support hourly scheduled refresh without breaking counts
My current dataset is around 8k–10k files and growing, so stability and consistency are the most important priorities.
You can proceed without needing access to my sheet — just ensure the script is easy to plug in and configure.
Please share:
• Full Apps Script code (ready to paste)
• Setup steps (including enabling Advanced Drive API if used)
• Instructions for running and debugging logs
Looking forward to the implementation.
Thanks
--
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 visit https://groups.google.com/d/msgid/google-apps-script-community/fde91ada-0872-447f-a533-63a8e5cf654fn%40googlegroups.com.
O uso do serviço avançado do Drive precisa ser habilitado antes do script rodar, e ele usa os mesmos métodos/parâmetros da Drive API pública. Os gatilhos instaláveis são apropriados para automações desse tipo, e PropertiesService é a forma suportada para manter estado simples entre execuções.
Como usar no dia a diaA regra implementada segue o que foi descrito na demanda: cada linha aponta para uma pasta principal em E; o script entra recursivamente nela; se um arquivo estiver em qualquer caminho que contenha uma subpasta chamada exatamente Folder 1, ele soma em F, e assim por diante até Folder 7; se não passar por nenhuma dessas, cai em Others. Arquivos diretamente na pasta principal também entram em Others. Isso reflete exatamente as confirmações da especificação.
Por que esse script tende a resolver os “zeros” e as contagens instáveisOs sintomas relatados eram: contagem zerando mesmo com arquivos existentes, valores variando entre execuções e dados antigos sem atualização. A solução acima reduz isso porque:
Segurança:
Performance:
Manutenção:
Eu implementei o checkpoint por lote/linha, que é o mais estável dentro do Apps Script para esse cenário. Isso já evita perder o progresso do processamento global. Um checkpoint ultradetalhado “no meio da árvore da pasta” também é possível, mas deixa o script bem mais complexo e aumenta risco de estourar armazenamento/estado no Apps Script. Para a maioria dos casos dessa demanda, checkpoint por linha + gatilho de continuação entrega o melhor equilíbrio entre confiabilidade e manutenção.
Logs e depuraçãoNo editor do Apps Script:
Você verá mensagens como:
No bloco CONFIG:
Sim — 8 mil a 10 mil arquivos é um volume viável, mas com uma observação importante: isso é viável em lote, com continuação por gatilho, e não como uma única execução “instantânea”. O Apps Script tem limites de execução e cotas, então o ponto não é só a quantidade total de arquivos, e sim quantos arquivos/subpastas cada linha precisa varrer e quantas linhas serão reprocessadas na mesma rodada.
Na prática, a solução que eu te passei escala bem para 8k–10k arquivos totais quando esses arquivos estão distribuídos em várias pastas e o processamento roda em batches. Ela usa paginação da Drive API, e o files.list aceita pageSize de até 1000 itens por página, então o script não tenta carregar tudo de uma vez. Isso ajuda bastante na estabilidade.
O ponto de atenção é este: se você tiver uma única linha apontando para uma árvore muito grande, com milhares de arquivos e muitas subpastas, essa linha pode demorar bastante para terminar dentro de uma execução do Apps Script. Nesse cenário, o gargalo não é a lógica do script em si, mas o tempo disponível por execução e as cotas do serviço.
Então minha resposta honesta é:
Para esse tamanho, eu classificaria assim:
Até ~10 mil arquivos totais
A solução atual deve funcionar bem na maioria dos casos, principalmente se:
Acima disso, ou com reprocessamento muito frequente
Eu melhoraria a arquitetura para não revarrer tudo sempre. O caminho mais eficiente seria usar a Drive Changes API para detectar só o que mudou e recalcular apenas as pastas afetadas, em vez de fazer full scan a cada atualização. A API de mudanças existe justamente para listar alterações em vez de reler toda a estrutura.
Resumindo: sim, 8k–10k arquivos é um alvo realista para a solução proposta, mas eu não venderia isso como “escalabilidade infinita”. Ela é boa para esse porte com batches e triggers; para volumes maiores ou atualizações muito frequentes, eu recomendaria uma versão com cache + checkpoint mais granular + Drive Changes API.
Se o objetivo for escalar isso com segurança e eficiência, posso atuar na evolução da arquitetura e implementação de uma solução mais performática e sustentável.
--
You received this message because you are subscribed to a topic in the Google Groups "Google Apps Script Community" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/google-apps-script-community/SvFBGQRMaxE/unsubscribe.
To unsubscribe from this group and all its topics, send an email to google-apps-script-c...@googlegroups.com.
To view this discussion visit https://groups.google.com/d/msgid/google-apps-script-community/a53e89d0-d189-494a-a1e7-a217a1f6049fn%40googlegroups.com.
You raise very valid concerns, and I agree with most of your assessment — especially regarding quotas and real-time constraints in Apps Script.
From a technical standpoint, the proposed approach (full recursive scan + batch continuation triggers) is viable for moderate-scale batch processing, but it does have clear limitations when applied to higher volumes or frequent refresh cycles.
For personal accounts, the 90-minute/day trigger runtime quota is indeed the primary bottleneck. Even with batching, a dataset in the range of 8k–10k files can require multiple chained executions to complete a full refresh, particularly when:
In such cases, repeated continuation triggers + scheduled refreshes can realistically exhaust the daily quota. So your concern here is absolutely justified.
The architecture I proposed is best suited for:
It is not designed for near real-time updates, and I would not position Apps Script as an ideal solution for that requirement.
One clarification: the Drive Changes API does not strictly require push notifications.
It can be used in a polling model, leveraging:
changes.getStartPageToken
changes.list
This allows tracking incremental changes since the last execution, significantly reducing the need for full rescans. This alone can drastically improve scalability within Apps Script constraints.
However, you are correct that:
In particular, Drive push notifications rely heavily on HTTP headers, and Apps Script’s doPost(e) interface does not provide full access/control over request headers, which limits its usability as a webhook receiver in this context.
So I’d summarize it this way:
For higher scale or responsiveness, a more suitable architecture would be:
To view this discussion visit https://groups.google.com/d/msgid/google-apps-script-community/c985aaca-3aaf-47b7-902d-db7b2eba6898n%40googlegroups.com.
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 visit https://groups.google.com/d/msgid/google-apps-script-community/CAJ-AUmiVObOt1h7skwQFvWJRmmwyV%3DJRaffBtUc58-o6s0K1cQ%40mail.gmail.com.