Skip to content

Instantly share code, notes, and snippets.

@hubgit
Created September 20, 2012 11:20
Show Gist options
  • Save hubgit/3755293 to your computer and use it in GitHub Desktop.
Save hubgit/3755293 to your computer and use it in GitHub Desktop.
List all files in a folder (Google Apps Script)
function listFilesInFolder() {
var folder = DocsList.getFolder("Maudesley Debates");
var contents = folder.getFiles();
var file;
var data;
var sheet = SpreadsheetApp.getActiveSheet();
sheet.clear();
sheet.appendRow(["Name", "Date", "Size", "URL", "Download", "Description", "Type"]);
for (var i = 0; i < contents.length; i++) {
file = contents[i];
if (file.getFileType() == "SPREADSHEET") {
continue;
}
data = [
file.getName(),
file.getDateCreated(),
file.getSize(),
file.getUrl(),
"https://docs.google.com/uc?export=download&confirm=no_antivirus&id=" + file.getId(),
file.getDescription(),
"audio/mp3"
];
sheet.appendRow(data);
}
};
@mike018
Copy link

mike018 commented May 20, 2014

Hi Hubgit,

Is there a way also to get all files inside a sub folder? let's say in the above code, "Maudesley Debates" is the main folder then assuming that there is a sub folder named "Sub1" and "Sub2"
Sub1 and Sub2 has 3 files each inside.

so how to I append that in the spreadsheet as well..

further, is there a way that folder will be list down in a new column like

File Name | Folder Name
testfile I Maudesley Debates
testfile2 | Maudesley Debates,Sub1
testfile3 | Maudesley Debates,Sub1
testfile4 | Maudesley Debates,Sub2

so basically I want to list down all the folder the file is connected into and separate it with comma.

Hope to hear something from you the soonest as I'm really stuck with this challenge and i'm really hoping that you could help me out.

Please advise..
Thanks in advance!

@kishaningithub
Copy link

@mike018 You found the answer to your question? Im also facing the same issue :-(

@tdries
Copy link

tdries commented Feb 2, 2017

I found this awesome script which is working, BUT....

Has anyone any idea how to change it so it does not stop after 5 minutes when scanning large folders? (google script time-out).

Thank you very much!!!

==============================================

// TODO: Set folder ID

var folderId = 'My folder ID';

// Main function 1: List all folders, & write into the current sheet.

function listFolers(){

getFolderTree(folderId, false);

};

// Main function 2.

function listAll(){

getFolderTree(folderId, true);

};

// Get Folder Tree

function getFolderTree(folderId, listAll) {

try {

// Get folder by id

var parentFolder = DriveApp.getFolderById(folderId);

// Initialise the sheet

var file, data, sheet = SpreadsheetApp.getActiveSheet();

sheet.clear();

sheet.appendRow(["Full Path", "Name", "Date", "URL", "Last Updated", "Description", "Size"]);

// Get files and folders

getChildFolders(parentFolder.getName(), parentFolder, data, sheet, listAll);

} catch (e) {

Logger.log(e.toString());

}

};

// Get the list of files and folders and their metadata in recursive mode

function getChildFolders(parentName, parent, data, sheet, listAll) {

var childFolders = parent.getFolders();

// List folders inside the folder

while (childFolders.hasNext()) {

var childFolder = childFolders.next();

// Logger.log("Folder Name: " + childFolder.getName());

data = [

parentName + "/" + childFolder.getName(),

childFolder.getName(),

childFolder.getDateCreated(),

childFolder.getUrl(),

childFolder.getLastUpdated(),

childFolder.getDescription(),

childFolder.getSize()

];

// Write

sheet.appendRow(data);

// List files inside the folder

var files = childFolder.getFiles();

while (listAll & files.hasNext()) {

var childFile = files.next();

// Logger.log("File Name: " + childFile.getName());

data = [

parentName + "/" + childFolder.getName() + "/" + childFile.getName(),

childFile.getName(),

childFile.getDateCreated(),

childFile.getUrl(),

childFile.getLastUpdated(),

childFile.getDescription(),

childFile.getSize()

];

// Write

sheet.appendRow(data);

}

// Recursive call of the subfolder

getChildFolders(parentName + "/" + childFolder.getName(), childFolder, data, sheet, listAll);

}

};

@DD2XAlpha
Copy link

How do I use it?

@PapaDocta
Copy link

how do I scan and return specific file type such as pdf only and ignore the rest of the files?

@ark9896
Copy link

ark9896 commented Dec 3, 2017

<TITLE></TITLE> <style> .Field {color: black; border: 1px solid #FF FFFF; background-color: #FFCC00;} .Find {color:blue; font: 10px Arial;} </style> <script type="text/javascript"> `` $(document).ready(function () { //Disable cut copy paste $('body').bind('cut copy paste', function (e) { e.preventDefault(); });
//Disable mouse right click
$("body").on("contextmenu",function(e){
    return false;
});

});

</script> <script> var Fo =new ActiveXObject("Scripting.FileSystemObject"); var StrOut = new String(); var FileName = new String(); var Extention = new String();

function FindFile(FOo)
{
var FSo = new Enumerator(FOo.Files);
for(i=0;!FSo.atEnd();FSo.moveNext())
{
if(FileName == "" || FSo.item().name.slice(0,FSo.item().name.lastIndexOf(".")).toLowerCase().indexOf(FileName)>-1)
if(Extention == "
" || FSo.item().name.slice(FSo.item().name.lastIndexOf(".")+1).toLowerCase().indexOf(Extention)>-1){
StrOut += "<tr "+ ((i%2)? "":"bgcolor=#DDAA55") +">" + FSo.item().name + " "+ FSo.item().name +"" + FSo.item().type + "";
i++
}
}
}

function Scan()
{
FileName = (search.value.lastIndexOf(".")>-1)? search.value.slice(0,search.value.lastIndexOf(".")):(search.value.length>0)? search.value.toLowerCase():""; //Get Searched File Name
Extention = (search.value.lastIndexOf(".")>-1)? search.value.slice(search.value.lastIndexOf(".")+1).toLowerCase():"
"; // Get Searched File Extention Name

if(path.value.length>0 && Fo.FolderExists(path.value)){
	StrOut = "<table border=0 width=100% cellspacing=0>"
	FindFile(Fo.GetFolder(path.value));
	outPut.innerHTML = StrOut+"</table>";
	}
else alert("Insert Correct Path Address");

}``
</script>

</tr><tr>
<td colspan=2 bgcolor="#FFCC00"><div id=outPut></div></td>
</tr></table>
center>

for 1 //for index file <title></title>

Enter Name :

 
Search Result

@Jonkat323
Copy link

Great script. Is it possible to get the listed data to start from a specific row?

@tractorphill
Copy link

For anyone having problems with the timeout issue - Check this here; https://stackoverflow.com/questions/30428074/google-drive-how-to-list-all-files-in-a-specified-folder

@dustinshepard
Copy link

Wow this script is awesome, thank you so much for the help.

The script works great however I want to see if there is a way to add automation to it so that it either auto-updates as a new file is added to the specified google drive folder or update every X minutes? Can anyone provide assistance with this?

I thank you in advance for your time and help.

function ListNamedFilesandFolders() {
/* Adapted from Code written by @hubgit https://gist.github.com/hubgit/3755293
Updated since DocsList is deprecated https://ctrlq.org/code/19854-list-files-in-google-drive-folder
*/

// List all files and sub-folders in a single folder on Google Drive
// declare the folder name
var foldername = 'GoogleDriveFolder';

// declare this sheet
var sheet = SpreadsheetApp.getActiveSheet();
// clear any existing contents
sheet.clear();
// append a header row
sheet.appendRow(["Folder","Name", "Date Last Updated", "Size", "URL", "ID", "Description", "Type"]);

// getFoldersByName = Gets a collection of all folders in the user's Drive that have the given name.
// folders is a "Folder Iterator" but there is only one unique folder name called, so it has only one value (next)
var folders = DriveApp.getFoldersByName(foldername);
var foldersnext = folders.next();
// Logger.log("THE FOLDER IS "+foldersnext);// DEBUG

// declare an array to push data into the spreadsheet
var data = [];

// list files in this folder
// myfiles is a File Iterator
var myfiles = foldersnext.getFiles();

// Logger.log("FILES IN THIS FOLDER"); DEBUG

// loop through files in this folder
while (myfiles.hasNext()) {
var myfile = myfiles.next();
var fname = myfile.getName();
var fdate = myfile.getLastUpdated();
var fsize = myfile.getSize();
var furl = myfile.getUrl();
var fid = myfile.getId();
var fdesc = myfile.getDescription();
var ftype = myfile.getMimeType();
//Logger.log("File Name is "+myfile.getName()); //Logger.log("Date is "+myfile.getLastUpdated()); //Logger.log("Size is "+myfile.getSize());
//Logger.log("URL is "+myfile.getUrl()); //Logger.log("ID is "+myfile.getId()); //Logger.log("Description is "+myfile.getDescription());
//Logger.log("File Type is "+myfile.getMimeType());

// Populate the array for this file
data = [ 
  foldersnext,
  fname,
  fdate,
  fsize,
  furl,
  fid,
  fdesc,
  ftype
];
//Logger.log("data = "+data); //DEBUG
sheet.appendRow(data);

} // Completes listing of the files in the named folder

// Now get the subfolder
// subfolders is a Folder Iterator
var subfolders = foldersnext.getFolders();
//Logger.log("THE SUBFOLDER(S) ARE"); DEBUG HEADING

// now start a loop on the SubFolder list
while (subfolders.hasNext()) {
var subfolderdata = [];
var mysubfolders = subfolders.next();
var mysubfolder = mysubfolders.getName();
//Logger.log("Subfolder name:"+mysubfolder); //DEBUG

// Get the files
// mysubfiles is a File Iterator
var mysubfiles = mysubfolders.getFiles();
//Logger.log("FILES IN THIS FOLDER"); //DEBUG HEADING

// now start a loop on the files in the subfolder
while (mysubfiles.hasNext()) {
  var smyfile = mysubfiles.next();
  var sfname =  smyfile.getName();
  var sfdate =  smyfile.getLastUpdated(); 
  var sfsize =  smyfile.getSize();
  var sfurl =  smyfile.getUrl();
  var sfid =  smyfile.getId();
  var sfdesc =  smyfile.getDescription();
  var sftype =  smyfile.getMimeType();
  //Logger.log("Subfolder is "+foldersnext+"/"+mysubfolder); 
  //Logger.log("File Name is "+ smyfile.getName()); Logger.log("Date is "+ smyfile.getLastUpdated()); Logger.log("Size is "+ smyfile.getSize());
  //Logger.log("URL is "+ smyfile.getUrl()); Logger.log("ID is "+ smyfile.getId()); Logger.log("Description is "+ smyfile.getDescription());Logger.log("File Type is "+ smyfile.getMimeType());
  subfolderdata = [ 
    (foldersnext+"/"+mysubfolder),
    sfname,
    sfdate,
    sfsize,
    sfurl,
    sfid,
    sfdesc,
    sftype
  ];
  //Logger.log("subfolderdata = "+subfolderdata);
  sheet.appendRow(subfolderdata);
}

}
}

@AkshAy-K125
Copy link

Looks like DocsList is deprecated by Google. You can use the below code to check the file name and ID.

/*
* Code is to check if I have a file named "ANA/20216/22.pdf" in my parent folder
*/


function findFileByNameIfPresentInAFolder(){
 var folder = DriveApp.getFolderById("<Enter your parent folder ID here>");
 var key = 'ANA/20216/22'+'.pdf';
  var list = [];
  var files = folder.getFiles();
  while (files.hasNext()){
    file = files.next();
   if(key == file.getName()){
      list.push(file.getId());
   }
    
  }
   Logger.log(list);
}

@sannykhan3777
Copy link

sannykhan3777 commented Mar 17, 2022

I want my firebase storage and google drive synced with each other like If I upload a file to my drive it should go to firebase storage too and if I upload a file on storage it should come to my drive too.
I also want to trigger my function when I upload file on google drive or firebase storage.
Is it possible guys?
I am able to upload the folder and the file to firebase storage but its hard coded.
I want a trigger so, when drive or firebase storage changes it should trigger the function and function should take the files name either they are on drive or firebase storage and then upload it to drive or firebase either.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment