As title suggests
Got a script that's fetching a CSV from a specific G-Drive folder, which is currently filtering by a specific file name.
Is it possible to just say 'get the latest file' from that folder instead of searching by the specific name?
Asking because multiple copies of the same file will be uploaded into the same folder (file name is content.csv, copies will either replace that file, or no doubt be uploaded as content(1).csv etc). So, therefore, assumed just trying to 'get the latest file' would be the best way?
Script:
function importCSVFromGoogleDrive() {
var fSource = DriveApp.getFolderById('xxxxxxxxxxxxx'); // folder where files are saved
var file = DriveApp.getFilesByName("content.csv").next(); // currently searching by file name
var csvData = Utilities.parseCsv(file.getBlob().getDataAsString()); csvData.splice(299,csvData.length-300);
var sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);
}
You can order the files by date so you can list the recently uploaded files, and when you hit an already downloaded file you just stop whole process.
https://developers.google.com/drive/api/v3/reference/files/list#orderBy
Try this:
function getLatest(){
var optionalArgs = {
orderBy:"modifiedDate",
q:"title='TITLE'"
};
var files = Drive.Files.list(optionalArgs).items;
Logger.log(files);
}
This will use the Advanced Services API to search for the files and order them by date. To use this code you'll need to enable Google Advanced Services, which allows you to use the APIs directly. You should also look at the File Resource to know what properties are available. Lastly, files holds an array of the files returned by the list.
Related
I have a folder in Google Drive, where there are some files. I want to retrieve all of these file information, and that's all I want. There are many other files in other folders, but I don't need them. However, my following code is showing all files' names. How can I limit the result only to the files in the specified folder?
//Folder ID
var myFolderId = "XXXXXXXXXXXXXXXXXXXXXXXXX";
var files = DriveApp.getFolderById(myFolderId).getFiles();
while(files.hasNext())
{
var file = files.next();
Logger.log(file.getName());
}
For now, there are only 4 files in this folder, but the log shows the entire file names in my Google Drive. I don't know what I am doing wrong, because I am specifying the folder with ID. How come it is returning every file in Google Drive?
Answer:
Your code already works great!
Further information:
Google Apps Script doesn't allow the running of global code as specific functions need to be declared and run, at least, not in the same was as locally-run code. The global variables are static and can not be changed in the runtime.
Things you can do:
As Cooper mentioned in their comment - all you need to do is put your code in a function, call the function and you're set. The code works great:
function functionName(){
var myFolderId = "XXXXXXXXXXXXXXXXXXXXXXXXX";
var files = DriveApp.getFolderById(myFolderId).getFiles();
while(files.hasNext())
{
var file = files.next();
Logger.log(file.getName());
}
}
As a side-note: if you really want to use a global scope (or at least. use an emulation of it), the PropertiesService is available to you, though you'd still have to set them in a function and run a function to retrieve them:
function setVars(){
PropertiesService.getScriptProperties().setProperty('myFolderId', 'XXXXXXXXXXXXXXXXXXXXXXXXX');
}
function listFiles(){
var files = DriveApp.getFolderById(PropertiesService.getScriptProperties().getProperty('myFolderId')).getFiles();
//continue this code
}
With the help of a nice article (https://www.labnol.org/internet/google-drive-tree/21198/), I just setup my first google script in Google Drive.
Quick Question:
How may I get a running script /myFolder1/music/myFirstScript.gs, to determine it's running in /myFolder1/music?
This didn't work. I got the Url but nothing in the log file showed the correct answer.
var files = DriveApp.searchFiles('title contains "GoogleTreeAgenda5"');
while (files.hasNext()) {
var file = files.next();
Logger.log(file.getName());
Logger.log(file.getUrl());
Logger.log(file.getDownloadUrl());
Logger.log(file.getDescription());
Logger.log(file.getOwner());
Logger.log(file.getParents());
Logger.log(file.getParents()[0].getName());
Logger.log("------------------------------");
}
Longer Behind The Scenes Reason:
The file will be modified a bit so that each month I will create a new tree structure off the root with agenda topics and the script will create an html file from the directory tree which is based on topic. Basically it will be an outline creator based on the current location of the script file. So Let's say this month it's in: /myFolder1/music (so in other words it's /myFolder1/music/myFirstScript.gs. The script needs to determine that folder is /myFolder1/music so that I can have it print the tree structure starting from the folder it's located in to an html file..
In the example application provided by the site I noted above, there are 2 options to print the tree from the google script:
1) Tree starting from the root folder
var parentFolder = DriveApp.getRootFolder();
2) Starting from a particular folder (but I can't figure out and will need "Folder_Name" to be determined dynamically from the location where the .gs file is located)
var parent = DriveApp.getFoldersByName("FOLDER_NAME").next();
I've used getScriptId() this will:
Gets the script project's unique id.
This id is also the unique id in the Google Drive. Then from there, create a recurring getParents() until you reach the root folder.
Here is the complete code:
function myFunction() {
var scriptID = ScriptApp.getScriptId();
// Logger.log(scriptID)
// Log the name of every parent folder
var driveFile = DriveApp.getFileById(scriptID);
var parentFolder = driveFile.getParents();
while (parentFolder.hasNext()) {
var folder = parentFolder.next();
Logger.log(folder.getName());
}
}
NOTE:
There is no real or concrete path since a file can have multiple parents. It is also stated here in this related SO post.
Hope this helps.
I've spent several days searching this and I find answers pretty close to what I'm looking for but not exactly it. I'm new to coding and trying to learn based on need + researching on the side.
Open Google sheet, inside would have a button that runs this script (I can do this now).
This sheet is used repeatedly and can be saved in different folders. It's used as a request form, in the same folder are additional documentations for the request.
I want the script to send the Active Sheet as well as 'All' other files in the same folder as an email attachment (could possibly use a link but rather the entire file).
It will then be sent to the recipients (that part of the code is not listed below)
Below is what I have so far: (This lists all files in the active folder and puts it in the Sheet, this is not necessary if there is another way). I then need it to attach each file-ID as an attachment. The folder structure is something like
Also, I'm still trying to understand setting the MIME, is there a way that can capture several different file types? PDF, JPG and XLSX...?
root\Person_Name\UniqueFolderName\
function listFiles() {
var ss = SpreadsheetApp.getActiveSheet();
var ssID = SpreadsheetApp.getActive().getId();
var folderID = DriveApp.getFolderById(ssID).getParents();
var foldernewID = folderID.next().getId();
var files = DriveApp.getFolderById(foldernewID).getFiles();
var list = [];
list.push(['Name', 'ID', 'Size']);
while (files.hasNext()){
file = files.next();
var row = [];
row.push(file.getName(),file.getId(),file.getSize())
list.push(row);
}
ss.getRange(1,1,list.length,list[0].length).setValues(list);
Logger.log(list);
}
Also, the additional file types in the folder are .xlsx and .pdf
Any help would be greatly appreciated or pointing me in the right direction, I've tried several sites and most show attaching 1-2 files using their ID built in the script, my IDs will always be new and there could be more than 2-3+ so need a loop or something.
Thank you
I have an Adwords script that creates a new spreadsheet by using the command below:
var ssNew = SpreadsheetApp.create("Name document");
Is it possible to create this file in a specific folder of my Google Drive?
If so; the file will have the default access (view, edit, comment) permissions as the folder has, right?
If not; is it possible to give the created file a permission as in "Everyone in [company] can edit this file"?
Furthermore, is it possible to set some sort of expiration date for the file?
I'm planning on running the script daily and old files will no longer be relevant.
I can build some sort of check to find the old file, delete it and then run the script again, but if there is some sort of expiration function that would save me quite some code.
Thanks!
It is apparently not possible to create Spreadsheets within folders.
You'll have to use something like this:
function createNewSpreadsheetinFolder(){
var ssNew = SpreadsheetApp.create("Name document");
var targetFolder = DriveApp.getFolderById("0B1TY_1aqz3fpWktMa25LbVkzQTQ");
var ssnewFile = DriveApp.getFileById(ssNew.getId());
var ssFinal = ssnewFile.makeCopy("Name document", targetFolder);
ssnewFile.setTrashed(true);
try {ssFinal.addViewers(targetFolder.getViewers())} catch(e){};
try {ssFinal.addEditors(targetFolder.getEditors())} catch(e){};
}
The basic way to do that is turn conversion on when uploading files into Google Drive.
Another way is to select the xls file in the folder and convert it one by one by hand.
But if one has already many xls files uploaded in a folder, it may be faster to convert them with Google Apps Script than re-uploading again the files.
In my case:
once converted, I need to delete the xls files
all xls files are below the limits : "Uploaded spreadsheet files that are converted to the Google spreadsheets format can’t be larger than 100 MB, and need to be under 400,000 cells and 256 columns per sheet."
https://support.google.com/drive/answer/37603?hl=en
Thanks in advance;)
you should use the Advanced Drive Service, file update
This service must be enabled before use but the doc is pretty clear.
EDIT (following your comments)
(sorry for the long delay, I forgot this post)
This code will convert every XLS files in your drive to Google spreadsheet format (as long as their names have an .xls extension)
You must authorize the Drive extended ressource + API console (follow the instructions from the ressource/advanced services menu, see illustration below)
function importXLS(){
var files = DriveApp.searchFiles('title contains ".xls"');// you can also use a folder as starting point and get the files in that folder... use only DriveApp method here.
while(files.hasNext()){
var xFile = files.next();
var name = xFile.getName();
if (name.indexOf('.xls')>-1){ // this check is not necessaey here because I get the files with a search but I left it in case you get the files differently...
var ID = xFile.getId();
var xBlob = xFile.getBlob();
var newFile = { title : name+'_converted',
key : ID
}
file = Drive.Files.insert(newFile, xBlob, {
convert: true
});
}
}
}