using a variable in searchFiles Google script - google-apps-script

I have a third party program that pulls daily data into CSV files with the filename starting with the date it ran e.g. 17072017filename.csv
I need a seperate spreadsheet that will take a date input from the user, which will then search through the files in drive until it matches the date on the CSV file. Once i find the file i want i can then use getFileID() and getRange() to copy various values from that CSV file.
This is what i have at the moment (where cell A2 in the spreadsheet is where the user can type the date they want e.g. 17072017).
Issue seems to be that i can't pass the date (which will change everyday) as a variable in searchFiles(). Is this even possible?
This is what i have so far
function myfunction()
{
var inputDate = SpreadsheetApp.getActiveSheet().getRange("A2").getValue();
var files = DriveApp.searchFiles('title contains 'inputDate'');
while (files.hasNext())
{
var file = files.next();
Logger.log(file.getName());
}
}

How about a following modification?
From :
var files = DriveApp.searchFiles('title contains 'inputDate'');
To :
var files = DriveApp.searchFiles("title contains '" + inputDate + "'");
If I misunderstand your question, I'm sorry.

Related

Possible to rename multiple .csv in drive by content(s) of that file?

I got hundreds of datachunks (adding up daily) within a single gDrive Folder.
They all nare amed pretty similat like in_history.csv, in_history (1).csv, in_history (2).csv, out_history.csv, out_history (2).csv, ...
...
The all follow the exact same format, where colum three holds a date/time stamp:
Currency
Amount
Date (UTC)
USD
1000
2022-07-30 17:21:18
EUR
455
2022-04-13 18:04:06
...
I kindly ask someone to point me into a direction on how to rename each file based on "column" 3 (Date) so I end with filenames like
IN - 2022/04/13 - 2022/07/30.csv
IN - yyyy/mm/dd - yyyy/mm/dd.csv
OUT - yyyy/mm/dd - yyyy/mm/dd.csv
...
In a programmatical way I think I need something like this:
Loop through a defined folder to get all filenames
Loop through each containing .csv to get the lowest and highest date within colum 3
If filename contains "in" change filename to "IN - - .csv
I want to start using AppScript as I already found out how to trigger tasks on intervals and hope to learn more to utilize AppScript to ease up my daily life.
I lack o funderstanding on how to loop through the folder and get all files, from those files the rangse of "column" 3 (while there are no columns in .csv), extract the the smallest to highest date and modify the corresponding filename. Its a myth - not even sure if possible at all.
Any pointers or maybe even a starter I can wrap my brain around?
Note: The gDRive I am working in is a "personal" (not part of google organizational accounts/drives).
I've coded up something quickly without much error handling, it should give you the result based on your given data files,
The high-level idea is,
Get the files from the src folder.
Read each file's content, and extract the last column dates.
Sort the dates, then take the last item in the list as StartDate and the first item in the list as EndDate.
Create the new file name as {IN or OUT} - {StartDate} - {EndDate}.csv.
Rename the old file to the above file name.
function fileRenamingTask() {
var srcFolderId = "Your src folder id";
var destFolderId = "Your dest folder id, can be the same as src folder";
var SourceFolder = DriveApp.getFolderById(srcFolderId)
var Files = SourceFolder.getFiles();
while(Files.hasNext()) {
var file = Files.next();
var newFileName = getNewFileName(file);
rename(file, newFileName, destFolderId)
}
}
function getNewFileName(file) {
var rows = parseCsv(file);
var dates = []
for (i = 1; i < rows.length; i++) {
var dateTime = rows[i][2]; //assuming that the date item is always at the 3rd place
var dateStr = dateTime.split(" ")[0]; //split with the space and get the date part
dates.push(dateStr);
}
//sort the dates from latest to oldest
dates.sort( function(a, b) {
return new Date(b) - new Date(a);
}
)
var startDate = dates[dates.length - 1];
var endDate = dates[0];
var dateRange = `${startDate.replace(/-/g, '/')} - ${endDate.replace(/-/g, '/')}`;
var fileName = file.getName().split('_')[0].toUpperCase(); //get the first part of the filename in_history
return `${fileName} - ${dateRange}.csv`;
}
function parseCsv(file) {
var data = file.getBlob().getDataAsString();
var lines = data.split("\n");
var data = lines.map(function(lin){return lin.split(",")});
return data;
}
function rename(file, newFileName, folderId) {
var FileRename = file.makeCopy(newFileName);
var DestinationFolder = DriveApp.getFolderById(folderId)
DestinationFolder.addFile(FileRename);
}

"setOwner" not a function error - App Script

new to Google Scripts and I've looked through other posts on Stack Overflow as well but couldn't find a good answer.
I'm using data collected in Google Sheets to search for a file in Google Drive and transfer ownership of the file. I have google form that my users fill out, once submitted using an add-on I create a file based on the data that was submitted on the form. Now with the script, I'm trying to go gather certain information from sheets such as name, email, and company name -
Sample data image here.
What I have thus far:
function myFunction() {
//Get google sheets
var spreadsheetId = '1WvIIoYdmuIB5BQ3KgSYOOIiEn-K_GTzCkb7rITzRFck';
//get certain values from sheets
var rangeName = 'MDP Form!C25:E';
var values = Sheets.Spreadsheets.Values.get(spreadsheetId, rangeName).values;
if (!values) {
Logger.log('No data found.');
} else {
Logger.log('Name, Email, Customer:');
for (var row = 0; row < values.length; row++) {
// Print columns C and E, which correspond to indices 0 and 4.
Logger.log('Name: %s, Email: %s, Company: %s', values[row][0], values[row][1], values[row][2]);
//Utilities.sleep(90000);
//Searching through google drive
var name = (values[row][0]);
var email = (values[row][1]);
Logger.log(email);
var company = (values[row][2]);
var fileName = ('Mutual Delivery Plan ' + company + ' - ' + name);
Logger.log(fileName);
//add a 1 minute delay
//Utilities.sleep(90000);
//search for target folder
var folder = DriveApp.getFolderById('1whvRupu9hWdyl2CqSF-KvdVj8VE6iiQu');
//search for file by name within folder
var mdpFile = folder.searchFiles(fileName);
//transfer ownership
mdpFile.setOwner(email);
}
}
}
Problem:
The script works for the most part except for the last line "setOwner" is not a function. I've tried creating a separate function for this, used some other suggestions on other posts but still cannot get this to work. If anyone has ideas around what might I be missing here or suggestions that would be super helpful. Thanks!
I believe your goal as follows.
You want to transfer the owner of the file when the file with fileName is found in folder.
For this, how about this answer?
Modification points:
Although you say The script works for the most part except for the last line "setOwner" is not a function., if your script in your question is the current script, how about the following modification?
In your script, fileName is 'Mutual Delivery Plan ' + company + ' - ' + name, and fileName is used with var mdpFile = folder.searchFiles(fileName);. In this case, an error occurs. Because params of searchFiles(params) is required to be the query string.
I think that in your case, it's "title='" + fileName + "'".
Also searchFiles(fileName) returns FileIterator. This has already mentioned by the existing answer. Because at Google Drive, the same filenames can be existing in the same folder and each files are managed by the unique ID. So here, it is required to be modified as follows.
I think that in your case, the following flow is useful.
Confirm whether the file is existing using hasNext().
When the file is existing and the owner is you, the owner of the file is changed to email.
When above points are reflected to your script, please modify as follows.
Modified script:
From:
var mdpFile = folder.searchFiles(fileName);
//transfer ownership
mdpFile.setOwner(email);
To:
var mdpFile = folder.searchFiles("title='" + fileName + "'");
while (mdpFile.hasNext()) {
var file = mdpFile.next();
if (file.getOwner().getEmail() == Session.getActiveUser().getEmail()) {
file.setOwner(email);
}
}
If you don't need to check whether the owner is you, please remove if (file.getOwner().getEmail() == Session.getActiveUser().getEmail()) {.
Note:
In this case, when the file with the filename of fileName is not existing in folder, the script in the if statement is not run. Please be careful this.
Also, when there are several files with the same filename in folder, the owner of those is changed to email.
References:
searchFiles(params)
FileIterator
hasNext()
next()
getActiveUser()
Folder.searchFiles() returns a fileIterator not a file. If it's the only file with that name then you can usually getaway with mdpFile.next();
File Iterator

How to open a spreadsheet only by name of the corresponding file in Google Sheets?

I need a way to open a spreadsheet only by having the name of the corresponding file and the folder where the file is located. What I'm trying to do is creating a temporary copy of an active spreadsheet and reading information from the copy file rather than the active one. But unfortunately this copy file won't have a constant ID and URL as it's going to be erased every time after the script is done, and re-created with the next running of the script.
What I already tried is using the URL of the temporary file in order to open the spreadsheet itself, as you can see below.
But it's not useful for me, as I don't have a constant URL of this file (as it will be erased in the end of the script and have a new URL with the next script). But I have a constant name of the file, as well as this will be the only file in the respective folder.
What I also tried is looking for methods to open file only using its name (which is "temp_copy" in a 'temp_folder'). But I didn't find a working solution.
var report = SpreadsheetApp.getActiveSpreadsheet();
var temp_folder =
DriveApp.getFolderById("1EAsvVcFjIw5iGTeF_SxxQJLVlaLHl_pR");
DriveApp.getFileById(report.getId()).makeCopy("temp_copy", temp_folder);
var temp_copy = SpreadsheetApp.openByUrl(' ');
var hiddenSheet = temp_copy.getSheetByName('DATE');
var lastRow = hiddenSheet.getSheetValues(1,1,1,1);
var sheet = temp_copy.getSheetByName('forCSV');
var lastColumn = sheet.getLastColumn();
var activeRange = sheet.getRange(1,2,lastRow,lastColumn);
What I'm expecting as a result is to make the link between the 3rd line of the code (when making a copy of the basic file) and 5th line of the code onwards (when referencing specific range from the temporary file) only by using name of the file or respective folder. In theory it seems so easy, I should be missing something somewhere...
Many thanks in advance!
You can use DriveApp to get a FileIterator which contains the Sheet.
var file, files = DriveApp.getFilesByName("temp_copy");
if (files.hasNext ()){
file = files.next(); // Get first result for name
} else {
return "";
}
var sheet = SpreadsheetApp.openById(file.getId())

Google Apps Script - get URL of File in Drive with File Name

I am attempting to create a form in Google Spreadsheets which will pull an image file from my Drive based on the name of the file and insert it into a cell. I've read that you can't currently do this directly through Google Scripts, so I'm using setFormula() adn the =IMAGE() function in the target cell to insert the image. However, I need the URL of the image in order to do this. I need to use the name of the file to get the URL, since the form concatenates a unique numerical ID into a string to use the standardized naming convention for these files. My issue is that, when I use getFilesByName, it returns a File Iteration, and I need a File in order to use getUrl(). Below is an snippet of my code which currently returns the error "Cannot find function getUrl in object FileIterator."
var poNumber = entryFormSheet.getRange(2, 2);
var proofHorizontal = drive.getFilesByName('PO ' + poNumber + ' Proof Horizontal.png').getUrl();
packingInstructionsSheet.getRange(7, 1).setFormula('IMAGE(' + proofHorizontal + ')');
If you know the file name exactly, You can use DriveApp to search the file and getUrl()
function getFile(name) {
var files = DriveApp.getFilesByName(name);
while (files.hasNext()) {
var file = files.next();
//Logs all the files with the given name
Logger.log('Name:'+file.getName()+'\nUrl'+ file.getUrl());
}
}
If you don't know the name exactly, You can use DriveApp.searchFiles() method.
You're close - once you have the FileIterator, you need to advance it to obtain a File, i.e. call FileIterator.next().
If multiple files can have the same name, the file you want may not be the first one. I recommend checking this in your script, just in case:
var searchName = "PO + .....";
var results = DriveApp.getFilesByName(searchName);
var result = "No matching files";
while (results.hasNext()) {
var file = results.next();
if (file.getMimeType() == MimeType. /* pick your image type here */ ) {
result = "=IMAGE( .... " + file.getUrl() + ")");
if (results.hasNext()) console.warn("Multiple files found for search '%s'", searchName);
break;
}
}
sheet.getRange( ... ).setFormula(result);
You can view the available MimeTypes in documentation

Google Apps script to automate copies of Google Slides document

I'm trying to get a Google Apps script set up to automate saving of copies of a Google Slides document into a Drive folder each week. I realise that Slides is always backed up but I want to save a weekly copy of a constantly evolving document for reference.
Here's the script I'm trying to run:
function makeCopy() {
var timeZone = Session.getScriptTimeZone();
// generates the timestamp and stores in variable formattedDate as
// year-month-date hour-minute-second
var formattedDate = Utilities.formatDate(new Date(), timeZone , "yyyy-MM-dd' 'HH:mm:ss");
// gets the name of the original file and appends the word "copy"
// followed by the timestamp stored in formattedDate
var name = DocumentApp.getActiveDocument().getName() + " Copy " + formattedDate;
// gets the destination folder by their ID. REPLACE
// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx with your folder's ID
// that you can get by opening the folder in Google Drive
// and checking the URL in the browser's address bar
var destination = DriveApp.getFolderById("MyFolderID");
// gets the current Google Sheet file
var file = DriveApp.getFileById(DocumentApp.getActiveDocument().getId())
// makes copy of "file" with "name" at the "destination"
file.makeCopy(name, destination);
}
Any ideas where I'm going wrong?
You use DocumentApp which is for Google Docs, not slides. Instead, it should be SlidesApp.getActivePresentation().
Instead of hard-coding the folder ID, you can also use DriveApp to get the current file folder if you want to keep them together by using .getId() and .getFileById() followed by .getParents(). Although if you want to keep the copies in a separate folder then ignore this.