Automatically create new Google Drive folder from new files - javascript

I currently have a Zapier process running that automatically creates 3 new files uploaded from a form into a folder in my Google Drive called "New Users". Each file is formatted as firstname_lastname-filename.ext but this is not good in terms of organization.
Instead, I would like to dynamically create a new folder labeled as firstname_lastname containing the 3 new files every time they come in with the same firstname_lastname, rather than having a generic "New Users" folder filled with hundreds or thousands of files.
Unfortunately I'm a pretty novice programmer, so I'm not quite sure how to go about this using Apps Script.
Any advice?
I've thought about something like:
var files = DriveApp.getFiles();
while (files.hasNext()) {
var file = files.next();
Logger.log(file.getName());
if file.getName().includes("firstname_lastname") { // Check if a file name contains the string firstname_lastname
var folders = DriveApp.getFolders();
while (folders.hasNext()) {
var folder = folders.next();
Logger.log(folder.getName());
if folder.getName().includes("firstname_lastname") { // Check if a folder exists with a name that contains the string firstname_lastname
makeCopy(file.getName(), folder.getName()) // if said folder exists, make a copy of the the file and move it to that folder
} else { // if said folder does not exist...
var newFolderName = file.getName() // let the newFolderName be the same name as the file (I know this isn't right if I want the folder name to be firstname_lastname without the actual uploaded file name plus extension)
createFolder(newFolderName); // then create a folder that has the name newFolderName
makeCopy(file.getName(), folder.getName(newFolderName)) // then make a copy of the file and put it into the folder
}
}
}
}

You may want to first establish your root folder, "New Users". I've created a snippet for the flow:
//New Users Folder
var rootFolder = DriveApp.getFolderById("FOLDER_ID");
function myFunction() {
var files = rootFolder.getFolders();
while (files.hasNext()) {
var file = files.next();
Logger.log(file.getName());
if(file.getName() == fileuploadName){
//copy file if folder is existing
file.addFile(child)
}
else{
//create folder
var newFolder = rootFolder.addFolder(child);
newFolder.addFile(child)
}
}
Logger.log("Done")
}
This flow should be ok when you want to implement a dynamic creation of folder then migrate the files to a specific folder name.
Hope this helps.

Related

Error of duplication in root drive with google script while copying a file from one folder to another

So, I'm trying to copy a file which is updated automatically in my computer in a folder.
Thing is that every time the script runs, it copies the file in the selected folder but also creates a duplication in the root folder despite root isn't referred in the whole script
function moveFiles() {
var olderfiles = DriveApp.getFolderById("idfromdestinyfolder").getFiles();
while (olderfiles.hasNext()) {
var olderfile = olderfiles.next();
var pull = DriveApp.getFolderById("idfromdestinyfolder");
pull.removeFile(olderfile)
}
var files = DriveApp.getFolderById("idfromstartingfolder").getFiles();
while (files.hasNext()) {
var file = files.next();
var destination = DriveApp.getFolderById("idfromdestinyfolder");
file.makeCopy("nameofthefile",destination);
}
}
The first part olderfiles checks if a file exist in the destiny, and if exists, it removes it.
The second part copies the file from the starting folder to destination.
Thing is, every time it runs, it creates a copy in root which should not happen.
Is the first time I'm using google script
From the question
... it copies the file in the selected folder but also creates a duplication in the root folder despite root isn't referred in the whole script
The problem might be caused by the use of Class Folder.removeFile(child). Pleaser bear in mind that it's a deprecated method, the docs instructs to use Folder.moveTo(destination) instead.
If you are looking to send the file to the trash, then use Class File.setTrashed(true)
Related
Permanently delete file from google drive
Delete or Trash specific file in Drive
Try this makeCopy()
function makeCopy() {
var folderid = "folderid";
var fileid = "fileid";
var folder = Drive.Files.get(folderid, { "supportsAllDrives": true });
var newFile = { "fileId": fileid, "parents": [folder] };
var args = { "resource": { "parents": [folder], "title": "new Title" }, "supportsAllDrives": true };
Drive.Files.copy(newFile, fileid, args);
}

Save Gmail attachment to SHARED Google Drive

Goal:
Update code below to save attachments to a "Test" folder within "Shared drive"
So far I've been successful in saving attachments to "My Drive" using the gmail2gdrive script found on https://github.com/ahochsteger/gmail2gdrive
This script uses DriveApp.getRootFolder() to find the root folder, but does not look at shared drives.
I have the "Drive" Advanced Service set up and am able to at least view up to 10 folders in the Shared Drive using getSharedDrives(), but have been unsuccessful updating the code to transfer files to a shared drives.
Move a file from MyDrive to Shared Drive
function movefileToSharedDrive() {
const file = DriveApp.getFileById('');//fileid
const fldr = DriveApp.getFolderById('');//shared drive id
Drive.Files.update({"parents": [{"id": fldr.getId()}]}, file.getId(), null, {"supportsAllDrives":true});
}
Drive API Version 2 needs to be enabled
The Folder Drive ID can be found in the URL extension:
Folder Drive ID
Use the folders' Drive IDs (from above) to fill in the appropriate section of the code below (Copies files from desired folder into the shared folder):
function movefileToSharedDrive() {
makeCopy("", ""); //("From My Drive ID", "To Shared Drive ID")
}
function makeCopy(srcFolderId, dstFolderId) {
var srcFolder = DriveApp.getFolderById(srcFolderId);
var dstFolder = DriveApp.getFolderById(dstFolderId);
var files = srcFolder.getFiles();
while (files.hasNext()) {
var file = files.next();
var f = file.makeCopy(dstFolder);
if (file.getMimeType() == MimeType.GOOGLE_APPS_SCRIPT) {
Drive.Files.update({"parents": [{"id": dstFolderId}]}, f.getId());
}
}
}

why my app script code makes copy of the spreadsheet to the root directory of google drive in addition to the specific directory?

i have a spreadsheet and i save this sheet to a particular folder with the code below. if a file with the same name exists in this folder, it deletes the old one and then adds the new one. it was working well. but a few weeks ago it has started also to make copy to the root directory of google drive. it makes two copies of the sheet. one is to the directory i give and the other one (which is not wanted)is to the root directory.
i have been looking and looking but can't see the reason. can anyone help me about what is wrong with my code?
function copyToFolder_trigger(){
copyToFolder(folderID_ARSIV, sheet_Parklar);
}
function copyToFolder(folderid, spreadsheet){
var sheet = SpreadsheetApp.openById(spreadsheet);
var destFolder = DriveApp.getFolderById(folderid);
var date = getDailyDate();
if(isinFolder(folderid, date)){
var fileIterator = destFolder.getFilesByName(date);
while(fileIterator.hasNext()){
var file = fileIterator.next();
destFolder.removeFile(file);
}
}
DriveApp.getFileById(sheet.getId()).makeCopy(date, destFolder);
}
function isinFolder(folderId, filename){
var folder = DriveApp.getFolderById(folderId);
var files = folder.getFiles();
var res = false;
while (files.hasNext()) {
var file = files.next();
if(file == filename){
res = true;
break;
}
}
return res;
}
archive folder
root folder
Frankly, I have no idea what's going on. But when I changed the line:
destFolder.removeFile(file);
to:
file.setTrashed(true);
It started work well. For me. For now...

How to move PDF files from a parent folder to a subfolder which has the same name as the file

I am working on a project which sends PDFs from a Wordpress website to a Google Drive. The files are PDFs of people who registered for certain events, which are held in certain cities. These PDFs are all sent to a parent folder "registrations". What I need to achieve is to automatically send these PDFs to subfolders like Amsterdam, Rotterdam, Woerden, Westland etc.
The PDFs are all sent to a parent folder "registrations". What I need to achieve is to automatically send these PDFs to subfolders like Amsterdam, Rotterdam. The names of the PDFs are the city names (e.g. Amsterdam).
In conclusion, the question basically is: how could I achieve to send a file with the name Amsterdam to a subfolder with the name Amsterdam, and a file with the name Rotterdam to a folder with the name Rotterdam?
EDIT: I am working on the script, but it is not complete yet. The script below searches for files in a parent folder that contains "woerden" in its name. Next, it moves these files to a folder called "woerden". This works, but the problem is that I will have to create about 300 different scripts to be able to automate the entire process. I am therefore wondering if it is possible to make this script more dynamic. For example, if a file with a name that contains -woerden- it is sent to a folder with the name woerden, and if a file with a name that contains -westland- it will be sent to a folder with the name westland.
function SearchFiles() {
// Parent folder
var parentFolder = DriveApp.getFolderById('15azR1-Fic_F_wPZHzXWKblIyxBB_GVsW'); //parent folder which will be scanned for duplicates
// Log the name of every file in the user's Drive whose name contains "westland".
var files = DriveApp.searchFiles(
'title contains "westland"');
while (files.hasNext()) {
var file = files.next();
// Remove the file from all parent folders
var parents = file.getParents();
while (parents.hasNext()) {
var parent = parents.next();
parent.removeFile(file);
}
DriveApp.getFolderById('1mSW3-uqv_F1m-TfLa_JyGRVK9-sGJYTj').addFile(file);
}
}
I hope that I asked my question clearly. Please let me know if you need some more information.
Cheers,

Creating zip file only contains pdf

In my script I am trying to create a folder, create a date-stamped-document in said folder, create a sub folder, and copy some documents into that sub folder.
All of this works great. When I try to zip the parent folder via either of the methods found here: Creating a zip file inside google drive with apps script - it creates a zip file with a sole PDF file that has the same name as the date-stamped-document. The zipped PDF is blank, and the subfolder isn't there.
Any insight about why this is happening would be great.
var folder = DocsList.createFolder(folderTitle);
var subFolder = folder.createFolder('Attachments');
subfolder.createFile(attachments[]); //In a loop that creates a file from every
//attachment from messages in thread
var doc = DocumentApp.create(docTitle); //Google Doc
var docLocation = DocsList.getFileById(doc.getId());
docLocation.addToFolder(folder);
docLocation.removeFromFolder(DocsList.getRootFolder());
//Everything works fine, I can view file and subfolder, and subfolder's documents
//This is where the problem is:
var zippedFolder = DocsList.getFolder(folder.getName());
zippedFolder.createFile(Utilities.zip(zippedFolder.getFiles(), 'newFiles.zip'));
//this results in a zipped folder containing one blank pdf that has the same title as doc
The DocsList service has been deprecated so Phil Bozak's previous solution no longer works. However, refer to another SO question for solution that works with DriveApp class.
This is a great question. It does not seem that the zip function has the ability to zip sub folders. The reason that your script doesn't work is because you only select the files from the folder.
A solution would be to zip each of the subfolders and store that in the one zipped file. You can use the function that I wrote for this.
function zipFolder(folder) {
var zipped_folders = [];
var folders = folder.getFolders();
for(var i in folders)
zipped_folders.push(zipFolder(folders[i]));
return Utilities.zip(folder.getFiles().concat(zipped_folders),folder.getName()+".zip");
}
This recursively zips all subfolders. Then you need to create the file with something like
DocsList.getFolder("path/to/folder/to/store/zip/file").createFile(zipFolder(folderToZip));
I will put in a feature request to allow subfolders to be zipped.

Categories

Resources