Google Script Separate Folders and Subfolders - google-apps-script

I'm a beginner coder and am using code I found on the internet to create a list of all folders and subfolders from a Google Drive folder. I'm able to generate that list, but I have two issues:
How do I increase the run speed? I keep hitting the max of 6 minutes for executing a function.
How can I tell the difference between a folder and subfolder? I can run the code and see the list of folders, but I would like a way to differentiate between what is a primary folder and what are the secondary folders within that folder before looking at a new one.
I appreciate any help I can get.
Heres the code I'm using
function listFolderContents() {
var foldername = 'name of folder';
var folderlisting = 'listing of folder ' + foldername;
var ss = SpreadsheetApp.create(folderlisting);
var sheet = ss.getActiveSheet();
var folders = DriveApp.getFoldersByName(foldername)
var folder = folders.next();
//listFilesInFolder(folder, sheet);
traverseFolder(folder, sheet);
};
function traverseFolder(folder, sheet) {
listFilesInFolder(folder, sheet);
var subFolders = folder.getFolders();
while (subFolders.hasNext()) {
traverseFolder(subFolders.next(), sheet);
}
}
function listFilesInFolder(folder, sheet) {
var foldername = folder.getName();
var contents = folder.getFiles();
sheet.appendRow( [foldername] );
while(contents.hasNext()) {
var file = contents.next();
}
}

Related

Insert all photos from one google drive folder into google Sheet?

I am not much of a coder, and only smart enough to modify code slightly. But I am hoping someone can help me. I am looking to upload all images in a google folder into a spread sheet with a script. I need the folder name to be changeable based on a cell, so I can change the name of the cell to a different folder run the script and the script will bring in all photos from the folder. Some folders might have 5 photos, others might have 25 photos. I have been able to figure it out but only if I reference the actual photo, and not just reference the name of the folder and have it import all. Any and all help is thanked in advance.
function insertImages() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const nameF = 'Folder'; // Sheet Name of the sheet containing the Folder Name
const rangeF = 'A1'; // Cell containing the Folder Name
const nameT = 'Target'; // Sheet Name of the sheet to insert images
let row = 2; // Starting row to insert
const col = 1; // Column to insert
const sheet = ss.getSheetByName(nameT);
const folderName = ss.getSheetByName(nameF).getRange(rangeF).getValue();
const folders = DriveApp.getFoldersByName(folderName);
while (folders.hasNext()) {
const folder = folders.next();
const files = folder.getFiles();
while (files.hasNext()) {
const file = files.next();
sheet.insertImage(file.getBlob(), col, row++);
}
}
}
by ID
function importImgs1() {
var folderID = '1ZfWEnxtKQiuz8V9j2ckgIZRHRMmYc7rH';
var sh = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('import images');
sh.clear();
sh.appendRow(["name", "image"]);
var folder = DriveApp.getFolderById(folderID);
var data = [];
var files = folder.getFiles();
while (files.hasNext()) {
var file = files.next();
data = [
file.getName(),
"=image(\"https://docs.google.com/uc?export=download&id=" + file.getId() +"\")",
];
sh.appendRow(data);
}
}
by Name
function importImgs2() {
var folderName = 'img';
var sh = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('import images by name');
sh.clear();
sh.appendRow(["name", "image"]);
var folders = DriveApp.getFoldersByName(folderName);
var foldersnext = folders.next();
var data = [];
var files = foldersnext.getFiles();
while (files.hasNext()) {
var file = files.next();
data = [
file.getName(),
"=image(\"https://docs.google.com/uc?export=download&id=" + file.getId() +"\")",
];
sh.appendRow(data);
}
}

Get all files in Folder and Subfolders Gscript

I have a gscript that will return all the files in a folder adn write to the open spreadsheet. I would like to add the files in all the subfolders as well but can't quite make it work. Here is the script for the files in the folder with the contents of the subfolders:
function getFiles() {
// Get the active spreadsheet file and the active sheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ssid = ss.getId();
// Look in the current folder e.g. if this spreadsheet is in 'My Folder'
// this routine will return all of the files in 'My Folder'.
var ssparents = DriveApp.getFileById(ssid).getParents();
var sheet = ss.getActiveSheet();
// Clear the area, add the headers ready for results
var headers = [["Full Folder Ref", "File Name", "Last Updated", "File Owner", "File URL", "In Folder"]];
sheet.getRange("A1:F").clear();
sheet.getRange("A1:F1").setValues(headers);
// Loop through all the files, add the values to the spreadsheet.
var folder = ssparents.next();
var files = folder.getFiles();
var i=1;
while(files.hasNext()) {
var file = files.next();
// get the full folder ref
var fileParents = file.getParents()
folders = [];
while (fileParents.hasNext()) {
fileParents = fileParents.next();
folders.push(fileParents.getName());
fileParents = fileParents.getParents();
}
// create the row
if(ss.getId() == file.getId()){
continue;
}
sheet.getRange(i+1, 1, 1, 6).setValues([[folders.reverse().join("/") , file.getName(), file.getLastUpdated(),file.getOwner().getName(), file.getUrl(), folder.getName() ]]);
i++;
}
}
Can someone help me add the subfolder files please.
thank you

Can I create a list of images in my Google Drive (including file name and share link)?

I have folders with several hundred images on Google Drive. I want to generate a spreadsheet by folder of the file name and also it's shareable link so that I can create a CSV file for bulk linking elsewhere.
I can bulk copy the shareable links, not with code, but by selecting all files in Google Drive, right clicking and using the share function. This produces a list of links that can be copy & pasted to a spreadsheet. However, I can't match them with file names.
I have found a script (below) to export a list of names and direct links (not share links), but can't get the order of either export to match up.
The script used to list file names and direct links was as follows:
// replace your-folder below with the folder for which you want a listing
function listFolderContents() {
var foldername = 'your-folder';
var folderlisting = 'listing of folder ' + foldername;
var folders = DriveApp.getFoldersByName(foldername)
var folder = folders.next();
var contents = folder.getFiles();
var ss = SpreadsheetApp.create(folderlisting);
var sheet = ss.getActiveSheet();
sheet.appendRow( ['name', 'link'] );
var file;
var name;
var link;
var row;
while(contents.hasNext()) {
file = contents.next();
name = file.getName();
link = file.getUrl();
sheet.appendRow( [name, link] );
}
};
// replace your-folder below with the folder for which you want a listing
function listFolderContents() {
var foldername = 'your-folder';
var folderlisting = 'listing of folder ' + foldername;
var folders = DriveApp.getFoldersByName(foldername)
var folder = folders.next();
var contents = folder.getFiles();
var ss = SpreadsheetApp.create(folderlisting);
var sheet = ss.getActiveSheet();
sheet.appendRow(['name', 'link']);
var file;
var name;
var link;
var row;
while (contents.hasNext()) {
file = contents.next();
name = file.getName();
link = "https://drive.google.com/uc?export=download&id=" + file.getId();
sheet.appendRow([name, link]);
}
};

Google Script get files names into spreadsheet issues

I made a code App Script that lists all the Folder Names and Files names into a Spreadsheet which works good until I rename one of the folders or file. Then the next time I run the script it will not include the renamed Folder/File into the Spreadsheet. Is there something I have done wrong in the script?
Thanks in advance for the help.
Link to spreadsheet: https://docs.google.com/spreadsheets/d/1T3eKmyXKhLCbcoMdZRzMQ1__-dL3bTlH0wMKaWVFJ1Y/edit?usp=sharing
Link to Google Script: https://script.google.com/d/1LVTe29Y3jDbElt8LM4ciZ8Kj0gPzmFAxawZaYmRaFvkkfrewtJ5fxO0B/edit?usp=sharing
Link to Folder: https://drive.google.com/drive/folders/1VPQC9Cp4QT0r_ILmq9c0nOsSSduqh6jg?usp=sharing
function listFolders(folder) {
var ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/1T3eKmyXKhLCbcoMdZRzMQ1__-dL3bTlH0wMKaWVFJ1Y/edit#gid=0');
var first = ss.getSheetByName("Sheet1");
first.clear("A2:D405");
var sheet = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/1T3eKmyXKhLCbcoMdZRzMQ1__-dL3bTlH0wMKaWVFJ1Y/edit#gid=0');
sheet.appendRow(["File Name", "URL", "Folder Name"]);
var folder = DriveApp.getFolderById('1VPQC9Cp4QT0r_ILmq9c0nOsSSduqh6jg');
var subfolders = folder.getFolders();
while (subfolders.hasNext()) {
//Logger.log(folder);
var name = subfolders.next();
while (subfolders.hasNext()) {
//Logger.log(folder);
var name = subfolders.next();
var files = name.getFilesByType('application/vnd.google-apps.spreadsheet');
var cnt = 0;
var file;
while (files.hasNext()) {
var file = files.next();
cnt++;
Logger.log(file);
Logger.log(cnt);
data = [
file.getName(),
file.getUrl(),
name, //folder name
];
sheet.appendRow(data);
};
}
}
}

A script to copy one sheet to various spreadsheets in a specific folder in Google Drive

I have a sheet which I need to copy to hundreds of spreadsheets in a given folder in Google Drive. I am just beginning with script and I do not know how to proceed because the script below just gives me an error. Thanks.
function myFunction() {
var source = SpreadsheetApp.getActiveSpreadsheet();
var sheet = source.getSheets()[0];
var folder = DriveApp.getFoldersByName('TEST FOR SCRIPT');
var contents = folder.getFiles();
for (var i = 0; i < contents.length; i++) {
file = contents[i];
}
sheet.copyTo(contents).setName('ANSWERS');
}
I was given this answer by someone within a community in Google+ and it works:
function copyToSheets() {
var source = SpreadsheetApp.getActiveSpreadsheet();
var sheet = source.getSheets()[1];
var folders = DriveApp.getFoldersByName('ID');
var firstFolder = folders.next();
var folderFiles = firstFolder.getFiles();
var thisFile;
while (folderFiles.hasNext()) {
thisFile = folderFiles.next();
var currentSS = SpreadsheetApp.openById(thisFile.getId());
sheet.copyTo(currentSS);
currentSS.getSheets()[currentSS.getSheets().length-1].setName('NAME');
}
}
This line of code:
var folder = DriveApp.getFoldersByName('TEST FOR SCRIPT');
returns a FolderIterator. Even if you only have one folder by that name, the getFoldersByName() method returns an object, that you can't use the getFiles() method on directly. The getFiles() method works on the Files Class. It is not available to the Folder Iterator. After you get the Folder Iterator, you must use the next() method to get the first (and probably only) folder in the object.
function getAllFilesInFolder() {
var source = SpreadsheetApp.getActiveSpreadsheet();
var sheet = source.getSheets()[0];
var folders = DriveApp.getFoldersByName('Folder Name Here');
var firstFolder = folders.next();
var folderFiles = firstFolder.getFiles();
var thisFile;
while (folderFiles.hasNext()) {
thisFile = folderFiles.next();
Logger.log(thisFile.getName());
};
};
And also use hasNext() to loop through the files. There doesn't seem to be an length property of the Files object.