Google script to get folder names within a parent folder - javascript

I need to get the names and URLs of the folders in a specified folder.
This is my attempt:
// set the folder to pull folder names from
var DDparentid = "IDhere";
var DDparent = DriveApp.getFolderById(DDparentid);
var DDfolders = DDparent.getFolders();
// iterate through folders in the folder
while (DDfolders.hasNext()) {
var folder = DDfolders.next();
// get folder name
Logger.log(folder.getName());
var DDnames = folder.getName();
// get the url
Logger.log(folder.getUrl());
var DDURLs = folder.getUrl();
}
This works for get file URLs, but I believe that folders are treated differently, and getfolder is used differently. I get an error stating that a string is not suitable in DriveApp.getfolder(). How should I be using getfolder?
EDITED: this runs, buit doesn't actually pull URLs or folder names. Both variables are undefined, but there are no errors.

You can try this :
var parentFolderId = "xxxxxxxIDxxxxxxx";
var parentFolder = DriveApp.getFolderById(parentFolderId);
var folders = parentFolder.getFolders();
var folder;
// iterate through folders in the folders fetched from parent folder
while (folders.hasNext()) {
folder = folders.next();
// get folder name
Logger.log(folder.getName());
// get the url
Logger.log(folder.getUrl());
}
This is an un-tested code, let me know if any issue arises I'll be happy to help us.
Thanks

Below lists all subfolder name and URL for specified folder:
function listSubFoldersInFolder(id) {
var dfolder = DriveApp.getFolderById('ENTER_PARENT_FOLDER_ID_HERE');
var contents = dfolder.getFolders();
var file;
var name;
var sheet = SpreadsheetApp.getActiveSheet();
var link;
sheet.clear();
sheet.appendRow(["Name", "Link"]);
while(contents.hasNext()) {
file = contents.next();
name = file.getName();
link = file.getUrl();
data = [name, link]
sheet.appendRow(data);
}
};

Related

Folder ID displays in Logger but the value wont allow me to move file to said folder ID

Okay so I have a sheet that I use to keep track of tips at work. Since its a shared sheet to keep it simple I just copy the sheet when its done and then archive the copied sheet to a subfolder based on the year.
All the code works perfect except when I try to move the copied sheet to the folder that I want.
Since I want to keep this as automatted as possible I have code to read the date within the sheet and either make a new folder for the year or move the file to the year folder that already exist.
For some reason the file will not move to the folder I want and I've tried multiple ways: within the 'makeCopy' function as well as the DriveApp.getFileById().moveTo();
Here is my code, error runs at bottom of code:
//Create folder if does not exists only
function createFolder(folderID, folderName){
var parentFolder = DriveApp.getFolderById(folderID);
var subFolders = parentFolder.getFolders();
var doesntExists = true;
var newFolder = '';
// Check if folder already exists.
while(subFolders.hasNext()){
var folder = subFolders.next();
//If the name exists return the id of the folder
if(folder.getName() === folderName){
doesntExists = false;
newFolder = folder;
return newFolder.getId();
};
};
//If the name doesn't exists, then create a new folder
if(doesntExists == true){
//If the file doesn't exists
newFolder = parentFolder.createFolder(folderName);
return newFolder.getId();
};
};
function start(){
//Parent folder (Location)
var FOLDER_ID = '1yinFsKfMP3_pWbM7BnOKcNRk-BDcty6E';
//Add the name of the folder here (Year of the sheet):
var year = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Instructions").getRange('L2').getDisplayValue();
var NEW_FOLDER_NAME = year;
//Create a new folder if a folder for the year doesnt exist (reverts to function:createFolder)
var myFolderID = createFolder(FOLDER_ID, NEW_FOLDER_NAME);
//Get the file ID of the parent file (Tip Tracker)
var getID = SpreadsheetApp.getActive().getId();
//Get the current name of the Tip Tracker (with dates)
var getName = SpreadsheetApp.getActive().getName();
//Create copy of Tip Tracker to be filed accordingly
var newFileID = DriveApp.getFileById(getID).makeCopy(getName + " ").getId();
var getNewFile = DriveApp.getFileById(newFileID);
getNewFile.moveTo(myFolderID);
Logger.log(newFileID);
Logger.log(myFolderID);
};
Try creating a getMyFolder as you did with getNewFile and moveTo the folder versus the ID.
const myFolder = DriveApp.getFolderById(myFolderID)
// ...
getNewFile.moveTo(myFolder)
File.moveTo(folder) takes a Folder, not an ID.

How to change name new creating folder with the subfolders

i want creating new folder with new name from cell in the sheet, and i want copy to this folder files and folders with the sourcedestiny.
Could you help me to solve my problem.
It is possible change name newFolder witout change name folders and subfolders- after his creating?
function copyFolderass() {
const sourceFolder = DriveApp.getFolderById('');
const destinyFolder = DriveApp.getFolderById('');
copyFolder(sourceFolder, destinyFolder);
}
function copyFolderContents(source, target) {
const filesIterator = source.getFiles();
while (filesIterator.hasNext()) {
const file = filesIterator.next();
file.makeCopy(file.getName(), target);
}
}
function copyFolder(sourceFolder, destinyFolder) {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("nameFile");
var name = ss.getRange("F4").getValue();
const newFolder = destinyFolder.createFolder(sourceFolder.getName());
copyFolderContents(sourceFolder, newFolder);
const foldersIterator = sourceFolder.getFolders();
while (foldersIterator.hasNext()) {
const folder = foldersIterator.next();
copyFolder(folder, newFolder);
}
}
Create Folders and Copy Files
Reads a sheet to obtain FilesFolder Id FolderFolder Id and new FolderName
It creates the new folder and copies all of the files from the Files Folder to the newly created folder.
It records the new folder id in FolderId Column.
It records all of the file ids in the FileIds column.
It put the date in the created column.
It doesn't do anything for rows that have content in Created
//FilesFolder FolderFolder FolderName FolderId FileIds Created
function createFolderAndCopyFiles() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName("Sheet0");
const shsr = 2;
let [hA, ...vs] = sh.getDataRange().getValues();
let idx = {};
let col = {};
hA.forEach((h, i) => { idx[h] = i; col[h] = i + 1; });
vs.forEach((r, i) => {
if (!r[idx["Created"]]) {
let dfldr = DriveApp.getFolderById(r[idx["FolderFolder"]]);
let fldr = dfldr.createFolder(r[idx["FolderName"]]);
let fldrid = fldr.getId();
sh.getRange(i + shsr, col["FolderId"]).setValue(fldrid);
let files = DriveApp.getFolderById(r[idx["FilesFolder"]]).getFiles();
let ids = [];
while (files.hasNext()) {
let file = files.next();
let fid = file.getId();
file.makeCopy(file.getName(), fldr);
ids.push(fid);
}
sh.getRange(i + shsr, col["FileIds"]).setValue(ids.join('\n'));
sh.getRange(i + shsr, col["Created"]).setValue(new Date());
}
});
}
Spreadsheet
You fill in the stuff in yellow the program fills in the rest and it won't make folders again if the Created Column not empty.
Thx Cooper for the answer,
but this is not that what i want to do.
on google drive i have a template of structure od catalogs.
my code is one of the part code of my main code. main code working like this
i click send email and then run my code with creating folder from temtlace
when is creating a have name of the template folder but i want just change one part of this line of my code.
instead of this line
const newFolder = destinyFolder.createFolder(sourceFolder.getName());
i want to just like this - the name of the creating folder is from cell F4.
the remaining names of the folders may stays like from template.
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("nameFile");
var name = ss.getRange("F4").getValue();
const newFolder = destinyFolder.createFolder(sourceFolder.setName(name));
but this line change ale name in subfolders i all structure catalog when is creating.

Trying to create a Google Drive Script to copy and move files

I'm horrible at coding so I'm sure this will need some work.
My Problem: My company does work for a lot of other companies (example Drive hierarchy photo attached). Each company we work with gets their own folder that is nested under the folder 'Shirts for other companies". We put all their assets into these folders (logos, mocks, quotes).
We want to build a script that will look into the individual company folders and take any file that starts with the word Mock and automatically copy it and put it into the database folder found in the picture below.
Here is the script have so far. but I'm having trouble getting into the subfolders (ford tshirts and designs). Not only that, but if it runs everyday the script will keep duplicating the files it has duplicated in the past which I want to avoid.
Script:
Function getTheFiles() {
var dApp = DriveApp;
var folderIter = dApp.getFolderByName("Shirts for other companies");
var folder = folderIter.next();
var filesIter = folder.getFiles();
var dataBase = folder.getFoldersByName("database1").next();
var i = 1;
while(filesIter.hasNext()) {
var file = filesIter.next();
var filename = file.getName();
if(filename = "mocking") {
file.makeCopy(dataBase);
}
logger.log(filename);
i++;
}
If I understood you correctly, you want to:
Copy all files from the different subfolders inside a folder called "Shirts for other companies", that start with the word mock, to the Database folder (which is also inside the main folder).
Avoid files getting copied many times.
If that's the case, you could do the following:
Search for all files in each subfolder of the main folder that start with mock, excluding the files inside Database folder. For this, you iterate through all files in each subfolder (after checking the subfolder is not named Database folder. For each file, you check that the name start with mock, using the method substring.
To keep track of which files are copied, and so avoid making duplicates, you can use PropertiesService, which can store key-value pairs. The id of every copied file is copied to the script property, and then, the next time the script runs, it checks whether the id is in the property. If that's the case, the file doesn't get copied again. One thing to notice is that script properties can only store strings, so that arrays have to be converted to a string every time we want to store a new id (via toString, and back to an array, via split.
The function below does all these things (check inline comments for more details):
function copyFiles() {
var mainFolder = DriveApp.getFoldersByName("Shirts for other companies").next();
var folders = mainFolder.getFolders(); // Get folder iterator from main folder
var databaseFolderName = "Database folder"; // You database folder name
var databaseFolder = mainFolder.getFoldersByName(databaseFolderName).next(); // Get databse folder
var idsArray = []; // Array to store the ids of the copied files
while (folders.hasNext()) { // Iterate through each folder in the main folder
var folder = folders.next();
if (folder.getName() !== databaseFolderName) { // Check current folder is not the database folder
var files = folder.getFiles();
while (files.hasNext()) { // Iterate through each file in each subfolder
var file = files.next();
if (file.getName().substring(0, 4).toLowerCase() === "mock") { // Check that file name starts with "mock"
// Get ids of the files that were copied in previous executions:
var key = "copied-ids";
var scriptProperties = PropertiesService.getScriptProperties();
var ids = scriptProperties.getProperty(key);
if (ids) idsArray = ids.split(",");
else ids = "";
// Get current file id:
var id = file.getId();
// Check that current file id is not in properties (not copied before):
if (idsArray.indexOf(id) === -1) {
file.makeCopy(databaseFolder); // Copy file to database folder
idsArray.push(id); // Add file id to the array of copied files
}
ids = idsArray.toString();
scriptProperties.setProperty(key, ids);
}
}
}
}
}
Reference:
PropertiesService
String.prototype.substring()
Array.prototype.toString()
String.prototype.split()
I hope this is of any help.
This function would search your entire Google Drive for files starting the the letter Mock and put Name, url, id, type (folder or file) into the active spreadsheet and tab named MoclList;
function getAllMocks() {
var ss=SpreadsheetApp.getActive();
var sh1=ss.getSheetByName('MocksList');
sh1.clearContents();
sh1.appendRow(['Name','Url','Id','Type']);
getFnF();
SpreadsheetApp.getUi().alert('Process Complete')
}
var level=0;
function getFnF(folder) {
var folder= folder || DriveApp.getRootFolder();
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('MocksList');
var files=folder.getFiles();
while(files.hasNext()) {
var file=files.next();
if(file.getName().toLowerCase().slice(0,4)=='mock') {
var firg=sh.getRange(sh.getLastRow() + 1,level + 1);
firg.setValue(file.getName());
firg.offset(0,1).setValue(Utilities.formatString('=HYPERLINK("%s","%s")',file.getUrl(),'FILE: ' + file.getName()));
firg.offset(0,2).setValue(file.getId());
firg.offset(0,3).setValue('File');
}
}
var subfolders=folder.getFolders()
while(subfolders.hasNext()) {
var subfolder=subfolders.next();
var forg=sh.getRange(sh.getLastRow() + 1,level + 1);
forg.setValue(subfolder.getName());
forg.offset(0,1).setValue(Utilities.formatString('=HYPERLINK("%s","%s")',subfolder.getUrl(),'FOLDER: ' + subfolder.getName()));
forg.offset(0,2).setValue(subfolder.getId());
forg.offsert(0,3).setValue('Folder');
//level++;
getFnF(subfolder);
}
//level--;
}

Rename all files in google drive by using google script

I want to rename my all Audio files in particular folder in my drive by using google script.
How to get original name of file? And replace with new name that will erase first 23 words and remain all name as it was. I didn't understand how to do that.
I try following script.
​ function non_native_file_name_changer(folderID,fileName,fileType,iterator) {
var folder = DriveApp.getFolderById('ID');
var files = folder.getFilesByType(fileType);
var count = 1
while(files.hasNext()){
var file = files.next()
if(iterator === true){
file.setName(file.getName().slice(-23));
}else{
file.setName(fileName);
};
};
};
function start(){
var folder_ID = "ID";
var file_name = "Audio";
var file_type = "audio/amr";
var have_a_count = true;
var go = non_native_file_name_changer(folder_ID,file_name,file_type,have_a_count);
};
This not work...
Please help.
To call all files from folder but no run.
Please help.
You say you want the files from a specific folder but you didn't open a specific folder. What happens if you use
var id = "xxxxxxxxxxxxxx";
var files = DriveApp.getFolderById(id).getFiles();
while (files.hasNext()) {
var file = files.next();
Logger.log(file.getName());
}

Creating a google app script that reads a file name from myDrive and places it in a folder based on file name

I'm having trouble creating an app script that can read a file name and from that file name move the file from myDrive to a designated folder. Ultimately I want to create an app that reads a naming convention of PR_P50_MP26_OtherContent.pdf and puts that file into the MP26 folder which is in the PR folder which is in the P50 Folder. When I run the script it sends my file to the wrong folder.
Goal: to move "PR_P50_MP286_LineLowering_2006_463.pdf" file into the PR Folder which is under the P50 Folder.
What happens when I run the code is it goes to the test folder in the else statement.
function MoveFiles(){
var files = DriveApp.getRootFolder().getFiles();
while (files.hasNext()) {
var file = files.next();
var packagedFile = file.getName();
if (packagedFile.indexOf("PR_P50"))
{
var destination = DriveApp.getFolderById("PR folder of P50 Folder");
destination.addFile(file);
var pull = DriveApp.getRootFolder();
pull.removeFile(file);
}
else{
var destination = DriveApp.getFolderById("My test Folder");
destination.addFile(file);
var pull = DriveApp.getRootFolder();
pull.removeFile(file);
}
}
}
There are quite a few issues with the code but the one error you mentioned can be fixed by replacing
var packagedFile = file.getname()
with
var packagedFile = file.getName()
You are using the getFolderbyId Which is looking for the folders given ID. Try getting the ID of the folder which should be part of the url. You should also declare your folder variable outside of the while loop.
https://drive.google.com/drive/folders/FOLDERIDHERE
This will atleast be able to get the file in the correct folder. If you wish to do it by folder name you will have to call on getFolderByName("PR folder of p50 folder") which will return a fileIterator so you will have to loop through it, but if you know there is only 1 folder with that name you will be able to set folder as var folder = folders.next(). Either way you choose to do it, you should now be able to get the file into your desired folder.
function MoveFiles(){
var files = DriveApp.getRootFolder().getFiles();
var 1stdestination = DriveApp.getFolderById("FOLDERIDHERE");
var 2nddestination = DriveApp.getFolderById("FOLDERIDHERE");
while (files.hasNext()) {
var file = files.next();
var packagedFile = file.getName();
if (packagedFile.indexOf("PR_P50"))
{
destination.addFile(file);
var pull = DriveApp.getRootFolder();
pull.removeFile(file);
}
else{
destination.addFile(file);
var pull = DriveApp.getRootFolder();
pull.removeFile(file);
}
}
}
I did something similar here
var JobFolder = DriveApp.getFolderById('MYFOLDERIDHERE');
//Other stuff here
if(!results.isBeforeFirst() ){
throw new Error('Job does not exist');
} else {
if(jobId in JobFolder.getFilesByName(jobId) )
{
var ss = SpreadsheetApp.open(jobId);
var url = ss.getUrl();
return {url:url, jobId:jobId};
} else
{
var ss = SpreadsheetApp.create(jobId);
ss.insertSheet('Job Materials');
ss.insertSheet('Job Operations');
ss.insertSheet('Job Notes');
ss.insertSheet('Employees Clocked On');
var temp = DriveApp.getFileById(ss.getId());
JobFolder.addFile(temp);
var url = ss.getUrl();
return {url:url, jobId:jobId};
}
}

Categories