Google Apps Script: Clone PDFs to new folder - google-apps-script

Afternoon all,
I am trying desperately to get a script to work and from what I can see it should work perfectly. I want to get a list of PDFs from the source folder and make copies of said PDFs into a secondary folder.
Here is the script:
var sourceFolder = DriveApp.getFolderById("source");
var targetFolder = DriveApp.getFolderById("target")
var files = sourceFolder.getFilesByType(MimeType.PDF);
while (files.hasNext()) {
var file = files.next();
file.makeCopy(targetFolder);
}
Am I missing something? Do I need permissions to use google scripts on drive? I am very confused.
Any help would be appreciated.

As per Marios mentioned in the comment, your code does work. Just make sure to copy the proper ID of the folder.
Your code should look like the code below when including the folder IDs
function myFunction() {
var sourceFolder = DriveApp.getFolderById("0B55C21aJsSBlfk9FTjRqOG8tb3hjR1N4MTU1YjVPNU4weGVhSldfU3F4OXladVVNMF9Ccms");
var targetFolder = DriveApp.getFolderById("1n9PJ_FFlJvlCRdWxHHJiTn4RF6-a1ypE");
var files = sourceFolder.getFilesByType(MimeType.PDF);
while (files.hasNext()) {
var file = files.next();
file.makeCopy(targetFolder);
}
}
Please see this to see how you get the folder ID.
Note that when you see a ?key=value format, don't include that and anything after that. They are called URL parameters and is not a part of the Folder ID

Related

Google App Script to rename a downloaded file

please assist.
I have a Google App Script that downloads an Excel file from the internet into my Google Drive. This is working. Thereafter the file needs to be renamed, this I'm struggling with.
Downloading of file working. Struggling with renaming...
function SaveToGoogleDrive()
var folderID = 'foldername'; // put id of the Google Drive folder
var folder = DriveApp.getFolderById(folderID) // get the folder
var file = UrlFetchApp.fetch("thewebsite");
folder.createFile(file);
//file.remame("NewDownloadedFile); // help?
}
Try this:
function SaveToGoogleDrive()
var folder = DriveApp.getFolderById('folderID');
var fileblob = UrlFetchApp.fetch("thewebsite").getBlob();
var file=folder.createFile(fileblob);
file.setName('NewDownLoadFile');
}

Move Folder Using App Script

So i'm brand new to JS and trying to build a program for internal operation at the company I work for. Below is the first bit of my code. I have a created a google form, and set a trigger so that when the submit button is clicked the below code will start. The trigger works and the first two functions work, but I cannot seem to get the Karrie folder to move from the root to the sub folder id (I do have the correct ID but omitted it from this post). Maybe I'm doing this all backwards so any help would be appreciated.
// Create Karrie Folder In Root
function start() {
var sourceFolder = "Property Template";
var targetFolder = "Karrie";
var source = DriveApp.getFoldersByName(sourceFolder);
var target = DriveApp.createFolder(targetFolder);
if (source.hasNext()) {
copyFolder(source.next(), target);}}
// Adds Property data to Karrie Folder
function copyFolder(source, target) {
var folders = source.getFolders();
var files = source.getFiles();
while(files.hasNext()) {
var file = files.next();
file.makeCopy(file.getName(), target);}
// Adds Photo Folders to Karrie Folder
while(folders.hasNext()) {
var subFolder = folders.next();
var folderName = subFolder.getName();
var targetFolder = target.createFolder(folderName);
copyFolder(subFolder, targetFolder);}}
// Moves Karrie folder to propertie folder
function MoveFiles(){
var files = DriveApp.getFolderByName("Karrie");
var destination = DriveApp.getFolderById("ID NA");
destination.addFolder(files);}
Debugger
I understood that MoveFiles() in your script doesn't work. If my understanding is correct, how about this modification?
Modification points :
In order to move a folder, it required to move the parent of the folder.
But when addFolder() is used to the folder, the folder has 2 parents.
So original parent has to be removed.
There is no getFolderByName(). Please use getFoldersByName().
Modified script :
function MoveFiles(){
var folder = DriveApp.getFoldersByName("Karrie").next();
var destination = DriveApp.getFolderById("ID NA");
destination.addFolder(folder);
folder.getParents().next().removeFolder(folder);
}
Note :
In this script, The folder and parent of "Karrie" supposes only one in the Google Drive, respectively.
References :
getFoldersByName()
addFolder()
removeFolder()
If I misunderstand your question, please tell me. I would like to modify it.
Edit 1 :
When you run this function, does the ID of Logger.log(r) show the folderId of "Karrie"?
function sample() {
var r = DriveApp.getFoldersByName("Karrie").next().getId();
Logger.log(r)
}
Edit 2 :
Please confirm and consider the following points.
Confirm the folder name and the existence of the folder again.
Run sample() and confirm folder ID of "Karrie".
Confirm whether there are no functions with the same name.
Can I ask you the folder ID of "Karrie"? If you cannot retrieve the folder ID using DriveApp.getFoldersByName("Karrie").next().getId(), I propose to use directly the folder ID of "Karrie".
Updated on March 30, 2022:
In the current stage, the files and folders can be moved using moveTo. Ref This method has added on July 27, 2020. When moveTo is used, the above script can be modified as follows.
function MoveFiles(){
var folder = DriveApp.getFoldersByName("Karrie").next();
var destination = DriveApp.getFolderById("ID NA");
folder.moveTo(destination);
}
Reference:
moveTo(destination) of Class Folder
As of 2020, the easier way I found to move a file is to use this function:
function moveToFolder(file, sourceFolder, destFolder) {
var file = DriveApp.getFileById(file.getId());
destFolder.addFile(file);
sourceFolder.removeFile(file);
}
Because of the first line, you can convert your Spreadsheet, Google Form, Document or others Google objects into a File.
Then we just use methods of the Folder class : https://developers.google.com/apps-script/reference/drive/folder
Notes:
If you created your file by using .create() your sourceFolder will be DriveApp.getRootFolder().
If you have multiple files to move, just iterate over them.

How to Create a Spreadsheet in a particular folder via App Script

Can anybody help me out,
I want to create a Spreadsheet through App Script in a particular folder. How to do that.
Presently I am doing as follow:
var folder = DocsList.getFolder("MyFolder");
var sheet = SpreadsheetApp.create("MySheet");
var file = DocsList.getFileById(sheet.getId());
file.addToFolder(folder);
file.removeFromFolder(file.getParents()[0]);
It is not working.......
As suggested by #Joshua, it's possible to create a Spreadsheet (in a specific folder) with the Advanced Drive Service (you'll need to activate this if you haven't already, by going into Services +, find Drive API and click Add).
var name = 'your-spreadsheet-name'
var folderId = 'your-folder-id'
var resource = {
title: name,
mimeType: MimeType.GOOGLE_SHEETS,
parents: [{ id: folderId }]
}
var fileJson = Drive.Files.insert(resource)
var fileId = fileJson.id
No need to move files around with this method !
folder = DriveApp.getFolderById("FOLDER_ID")
var ss = SpreadsheetApp.create("SPREADSHEET_NAME")
DriveApp.getFileById(ss.getId()).moveTo(folder);
You may use the above code to achieve the same without using advanced drive services
Since you can no longer create Google Docs (Docs or SpreadSheets) using DriveApp, nor use addToFolder because DocList is deprecated. There is only one way to create or "move" Google Docs or Google SpreadSheets..
//"Move" file to folder-------------------------------//
var fileID = '12123123213321'
var folderID = '21321312312'
var file = DriveApp.getFileById(fileID).getName()
var folder = DriveApp.getFolderById(folderID)
var newFile = file.makeCopy(file, folder)
//Remove file from root folder--------------------------------//
DriveApp.getFileById(fileID).setTrashed(true)
As you can see this DOES NOT move the file, it makes a copy with the same name in the folder you want and then moves the original file to the trash. I'm pretty sure there is no other way to do this.
The other answer is a bit short (and not very explicit).
While your approach is logic and should work if you replace
file.removeFromFolder(file.getParents()[0]);
with
file.removeFromFolder(DocsList.getRootFolder());
there is a better way to do the same job using the new Drive app and the Folder Class, Folder has a method to create a file and you can specify the file type using the mimeType enum.
Code goes like this :
function myFunction() {
var folders = DriveApp.getFoldersByName('YOUR FOLDER NAME'); // replace by the right folder name, assuming there is only one folder with this name
while (folders.hasNext()) {
var folder = folders.next();
}
folder.createFile('new Spreadsheet', '', MimeType.GOOGLE_SHEETS); // this creates the spreadsheet directly in the chosen folder
}
In July 27, 2020 there have been these updates:
The File class now has the following methods:
file.getTargetId(): Gets a shortcut's file ID.
file.getTargetMimeType(): Returns the mime type of the item a shortcut points to.
file.moveTo(destination): Moves a file to a specified destination folder.
The Folder class now has the following methods:
folder.createShortcut(targetId): Creates a shortcut to the provided Drive item ID, and returns it.
folder.moveTo(destination): Moves an item to the provided destination folder.
The following Folder class methods have been deprecated:
addFile(File)
addFolder(Folder)
removeFile(File)
removeFolder(Folder)
https://developers.google.com/apps-script/releases/#july_27_2020
So you can create a Spreadsheet file in a folder using file.moveTo(destination) method:
function createSpreadSheetInFolder(ss_new_name, folder_dest_id) {
var ss_new = SpreadsheetApp.create(ss_new_name);
var ss_new_id = ss_new.getId();
var newfile = DriveApp.getFileById(ss_new_id);
newfile.moveTo(DriveApp.getFolderById(folder_dest_id))
return ss_new_id;
}
var file_name = 'SPREADSHEET NAME';
var folder_id = 'DESTINATION FOLDER ID';
var new_ssId = createSpreadSheetInFolder(file_name, folder_id)
You can create a spreadSheet and then add it to the folder.
function createSpreadSheetInFolder(name,folder){
var ss = SpreadsheetApp.create(name);
var id = ss.getId();
var file = DriveApp.getFileById(id);
folder.addFile(file);
return ss;
}
folderId='your_folder_id'
name='my_new_ss'
folder=DriveApp.getFolderById(folderId)
createSpreadSheetInFolder(name,folder)
By using the folder.addFile method there's no need to use a temp file (no need to duplicate and remove file). Pretty straightforward !
I finally got the answer to my question. The following works
var file = DocsList.getFileById(sheet.getId());
var folder = DocsList.getFolder("MyFolder");
file.addToFolder(folder);
// remove document from the root folder
folder = DocsList.getRootFolder();
file.removeFromFolder(folder);
What is not working? Use getRootFolder in the last line.
Creating a new spreadsheet in a file can be done using this link as a reference.
createFile(name, content, mimeType)
Therefore using the enum MimeType we can do:
var folder = DriveApp.getFolderById("your-folder-id");
folder.createFile("My File Name","",MimeType.GOOGLE_SHEETS)

How can I pull information from spreadsheets in multiple folders in google script?

I already have a script which references all documents in ONE folder, but I need to reference multiple folders...
Script that works for one folder is:
var folder = DocsList.getFolder("My Spreadsheets");
var contents = folder.getFiles();
What I WANT to do is either
var masterfolder = DocsList.getFolder("My Folder that has multiple folders");
var folder = DocsList.getFolders(masterfolder)
var contents = folder.getFiles();
or
var folder = DocsList.getFolder("My Spreadsheets", "My Other Spreadsheets");
var contents = folder.getFiles();
I am quite newbye in this, but I think you'll have to do an iteration throught the subfolders:
var folder = DocsList.getFolders(masterfolder)
Here you dont't get one single folder; you get a set of them and you have to iterate trhout it with a for bucle. Something like:
for f in folders {
f.getfiles......
...
}
SURE you will get more precise answer.
Enrique

Adding File to a Folder

I'm trying to relocate newly created Google Docs file to a folder within google drive (using Google Apps).
var newFile = DocumentApp.create('New File');
var newFileID = Docs.getFileById(newFile);
var newFileRelocated = newFileID.addToFolder(newFolder);
And I'm getting "Cannot find method addToFolder(. (Line ...)". What am I doing wrong? They method drops down as an option when I'm writing it and still it cannot find it.
It's likely that your newFolder is not what's expected. Is it a string? Where you defined it?
Anyway, the parameter expected in addToFolder must be a Folder object you got using some other method in DocsList. e.g. DocsList.getFolder("/path/to/folder") or DocsList.getFolderById("folder-id") and so on.
There seems to be other "inconsistencies" with your code, I'll paste what I you're trying to do:
var newDoc = DocumentApp.create('New Google Doc');
//a DocumentApp file and a DocsList file are not the same object, although they may point to the same Google Doc
var newFile = DocsList.getFileById(newDoc.getId());
var folder = DocsList.getFolder("/path/to/folder"); //I'm assuming the folder already exists
newFile.addToFolder(folder);
The logic of this is not exactly as you tried...
here is a working example :
function myFunction() {
var newFile = DocumentApp.create('New File');
var newFileID = newFile.getId()
var newFolder = DocsList.createFolder('test Folder')
DocsList.getFileById(newFileID).addToFolder(newFolder)
}
Just to add to this, I recently dealt with this issue.
I noticed the default location is to store the DocsList.create() file in the root folder (aka My Drive).
This could lead to a real headache if you were doing lots of files.
I added this as the line after the .addToFolder()
newFile.removeFromFolder(DocsList.getRootFolder());
The following function is a simple google script to pass in an image URL.
function fetchImageToDrive_(imageUrl)
{
//Fetch image blob
var imageBlob = UrlFetchApp.fetch(imageUrl).getBlob();
//Create image file in drive
var folder = DocsList.getFolder('test Folder');
folder.createFile(imageBlob);
}