sort files by datecreated and remove old files with google apps script - arrays

Trying to make a simple google apps script to get files by name and order them by date created. If there are more than 5 files by the same name, delete all but the 5 newest files.
function tryme(){
var files = DriveApp.getFilesByName('thisFile');
var created = files.getDateCreated();
for(i in created) {
if(created[i] > 4){
file.setTrashed(true);}
}
}

You're trying to use a File method on a File Iterator (returns from getFilesByName() method).
Here is a solution for your issue:
function tryme(){
// Get the file Iterator
var files = DriveApp.getFilesByName('New Text File');
var fileArray = [];
// Put file on array
while(files.hasNext()){
var file = files.next();
fileArray.push([file, file.getDateCreated()]);
}
//While you have more than 5 files
while(fileArray.length>5){
var older = ["",new Date()];
var olderIndex;
// Get the older file
for(var i in fileArray){
if(fileArray[i][1].getTime() < new Date(older[1]).getTime()){
olderIndex = i;
older = fileArray[i];
}
}
// Delete the older file
fileArray.splice(olderIndex,1);
older[0].setTrashed(true);
}
}
Edit: I made a mistake by using DriveApp.removeFile() instead of File.setTrashed(true)

Related

how to copy files(links) from a column in sheets, to a specific folder in drive?

I'm trying to, on form submission, copy the files (which appear as links) from google sheets, specifically from column c, only, to a master folder. the links are to the pdfs within a folder, not a folder itself.
I end up with this fail code: Exception: Unexpected error while getting the method or property getFileById on object DriveApp.
copyFilesToMasterFolder # Code.gs:10
My file id is correct. I don't know what to modify?
function copyFilesToMasterFolder() {
var sheet = SpreadsheetApp.getActiveSheet();
var lastRow = sheet.getLastRow();
var fileLinks = sheet.getRange(2, 3, lastRow-1, 1).getValues();
var masterFolder =
DriveApp.getFolderById("1y5ezQEbS0fDr2TcOjum5wOy6xWHHJcy1");
for (var i = 0; i < fileLinks.length; i++) {
var fileLink = fileLinks[i][0];
var fileId = fileLink.split("/")[fileLink.split("/").length - 2];
var file = DriveApp.getFileById(fileId);
file.makeCopy(masterFolder);
}
}
1.In Google Sheets, select "Tools" from the top menu, then select "Script editor".
2.In the Script editor, paste the following code:
function copyFilesFromSheetToDrive() {
var sheet = SpreadsheetApp.getActiveSheet();
var folder = DriveApp.getFolderById("FOLDER_ID"); // Replace with the ID of the target folder
var column = 1; // Column number of the links in the sheet
var data = sheet.getDataRange().getValues();
for (var i = 0; i < data.length; i++) {
var file = DriveApp.getFileById(data[i][column - 1]);
folder.addFile(file);
}
}
1.Replace "FOLDER_ID" with the ID of the target folder in Google Drive. You can find the ID in the URL of the folder, e.g., "https://drive.google.com/drive/folders/FOLDER_ID".
2.Save the script and close the Script editor.
3.Back in Google Sheets, select the script from the "Run" menu, or run it by clicking the play button in the Script editor.
This script will copy all the files linked in the first column (column 1) of the active sheet to the specified folder in Google Drive. You can modify the script to copy files from a different column or from a different sheet by changing the column and sheet variables, respectively.

SuiteScript - Open, Read File

This is going to be a really stupid question - how do I open a file in the Filing Cabinet and read it in, line by line, using SuiteScript? Every example I can find online seems to start in the middle, taking for granted knowledge that I don't possess.
Is there a simple example somewhere online I've not found? All I need is for it to:
Open file (giving file name and folder)
Read the first line
Read the second line
....
Close the file.
In Suitescript 2.0 use the N/file module. The module can only be used in server side (not client) scripts. Reference Suite Answer Id: 43524 for N/file module and Suite Answer Id: 43520 for Script Types.
require(['N/file', 'N/record'], function(file, record) {
//use file name and folder and 'N/search' module to find the file id if necessary
// load file
var myFile = file.load({
id: '__' //enter the file internal id, absolute or relative file path
})
//get the # of lines
var arrLines = myFile.getContents().split(/\n|\n\r/);
// loop through each line, skipping the header
for (var i = 1; i < arrLines.length - 1; i++) {
//split the 1 line of data into an array. If the file was a csv file, each array position holds a value from the columns of the 1 line of data
var content = arrLines[i].split(',');
// get values from the columns of a CSV file
var column1 = content[0]; //first column
var column2 = content[1]; //second column
//can use the column data above to i.e. create new record and set default value, update existing records, write the data elsewhere
//to check each line for a given value
arrLines[i].includes('keyword'); //returns true or false
}
});
You can get the suitescript api documentation here
https://docs.oracle.com/cloud/latest/netsuitecs_gs/docs.htm
look at the file module
Let's keep it simple:
For SuiteScript 1.0:
var arrLines = nlapiLoadFile({fileinternalid}).getValue().split(/\n|\n\r/);
For SuiteScipt 2.0:
var arrLines = file.load({
id: {fileinternalid}
});
arrLines.getValue().split(/\n|\n\r/);
arrLines.description = 'My CSV File'
var fileId = arrLines.save();
...
// Add additional code

Firebase Storage: call random folder?

I'm working on a labeling tool for ML, and I want to be able to display the contents of a random folder on a React app so I can label them.I was thinking of finding the amount of folders, searching through the last available folder, and then delete from database. Repeat on refresh. Is this possible? I haven't been able to find out how to return the amount of folders in a directory.
var folders = [];
// Create a reference under which you want to list
var listRef = storageRef.child('path/to/files');
// Find all the prefixes and items.
listRef.listAll().then(function(res) {
res.prefixes.forEach(function(folderRef) {
// All the prefixes under listRef.
folders.push(folderRef);
});
}).catch(function(error) {
// Uh-oh, an error occurred!
});
var selected = []
// Select N=5 at random
for (i=0; i < 5 && folders.length > 0 ; i++){
var index = Math.floor(Math.random() * folders.length)
selected.push(folders[index])
folders.splice(index, 1);
}
You can list the files/folders inside a bucket path. Link. And select one at random of that list.
And similarly with delete files.

Move, Remove, and Replace information from Google Sheets with new entries using Google Script

I have created a Google Form that logs Timestamps, a numerical value, and an image file from its respondents to a Google Sheet. The image files are saved to an "imageFolder", but when I get too many responses, my imageFolder and Google Sheet get too large. Ideally, I want my imageFolder and its Google Sheet to stay below 50 entries.
I want to move the 10 oldest images in imageFolder to waitFolder. I want to save an array of those oldest values from column "How many?" before the entry is deleted. Then I want any new entries to replace the oldest ones who's information I have already save to waitFolder and the howMany() array (myArray10).
I know I have to move 10 images from "imageFolder" to "waitFolder" using functions along the lines of:
var text1 = "Response Form";
var text2 = "imageFolder";
var text3 = "Copy of imageFolder";
var text4 = "Wait Folder"
function moveFiles(sourceFileId, targetFolderId) {
var myFolder = DriveApp;
var files = myFolder.getFileById(sourceFileId).getFiles()
while (files.hasNext()) {
var file = files.next());
var dest = myFolder.getFolderById(targetFolderId);
dest.addFile(file);
var pull = DriveApp.getFolderById(sourceFolderId);
pull.removeFile(file);
}
}
function getMyId(text) {
var Ids = [];
var myFolder = DriveApp;
var folderIter = myFolder.getFoldersByName(text);
var folder = folderIter.next();
var folderIter = folder.getFiles();
while(folderIter.hasNext()) {
var file = folderIter.next();
var fileId = file.getId();
Ids.push(fileId);
}
return Ids
}
function getMyId10(text) {
var Ids = [];
var myFolder = DriveApp;
var folderIter = myFolder.getFoldersByName(text);
var folder = folderIter.next();
var folderIter = folder.getFiles();
for (var i = 0; i < 10; i++) { //Take the first 10
while(folderIter.hasNext()) {
var file = folderIter.next();
var fileId = file.getId();
Ids.push(fileId);
}
}
return Ids
}
function main() {
var imageFolderId = getMyId(text2);
var imageFolderId10 = getMyId10(text2);
var waitFolderId = getMyId(text4);
var Copy_imageFolderId = getMyId(text3);
moveFiles(imageFolderId, Copy_imageFolderId); //make a copy of imageFolder
moveFiles(imageFolderId10, waitFolderId); //Move first 10, remove from original
}
How can I move images from imageFolder to Copy_imageFolder?
How can I move the 10 oldest images from imageFolder to waitFolder?
How can I remove the 10 oldest images from imageFolder?
How can I limit the number of rows in my spreadsheet using Google script?
How can I overwrite my oldest rows with new entries/rows?
edit1: I am getting unexpected tokens in every function, and I am unsure why? It seems to pop up in the while loop of my function getMyId().
edit2: I see now why I was getting unexpected tokens. It seems that I was being irresponsible with my loops. I have replaced my 'while's with 'for's to amend this mistake.
edit3: I removed some unnecessary snippets of code to make it easier to follow.
edit4: Here is what my Form Response looks like in my Spreadsheet. The images are saved to subfolder imageFolder. But I can't grab the 10 array elements I want from the spreadsheet using howMany(). I also can't seem to move any of the files anywhere. When I call on moveFiles(), I get an unexpected error as soon as it asks for my DriveApp. How do I make my moveFiles() move my images from source to target folders?
Perhaps this is what you were looking for:
function moveFiles(sourceFolderId, targetFolderId) {
var srcFolder=DriveApp.getFolderById(sourceFolderId);
var desFolder=DriveApp.getFolderById(targetFolderId);
var files=srcFolder.getFiles();
while(files.hasNext()) {
var file=files.next();
desFolder.addFile(file);
srcFolder.removeFile(file)
}
}

how to change filename of exported SSRS report

I have created SSRS report and want to change the name of file with adding Date to it. I really appreciate your help.
Already tried https://reportsyouneed.com/ssrs-adding-date-to-exported-filenames/ solution and it doesn't work.
An easy alternative might be
An alternative approach to creating unique files for every delivery is to include a timestamp in the file name. To do this, add the #timestamp variable to the file name (for example, CompanySales#timestamp). With this approach, the file name is unique by definition, so it will never be overwritten.
See https://learn.microsoft.com/en-us/sql/reporting-services/subscriptions/file-share-delivery-in-reporting-services?view=sql-server-ver15
I got a perfect solution for this Issue.
This link works (very well) only if there is no parameter required before export.
Code in this link try to get the file name when you click on the file, means when download not ready and report looking for initial inputs.
But my file has date parameters in the beginning to input.
So I modify the code to wait till download is available and added to the end of "C:\Program Files\Microsoft SQL Server\MSRS10_50.MSSQLSERVER\Reporting Services\ReportManager\js\ReportingServices.js" file
function ModifyExportFileName(){
var rv=null;
var r= null;
var today =new Date();
var day= ("0" + today.getDate()).slice(-2);
var month = ("0"+ (today.getMonth() + 1)).slice(-2);
var year = ("0"+ today.getFullYear()).slice(-2);
var text= "DD";
try{
rv=this.$find("ctl31");
r=rv._getInternalViewer();
var url=r.ExportUrlBase;
var i = url.indexOf("FileName=");
}
catch(err)
{
//console.log(err);
setTimeout(ModifyExportFileName,2000);
return;
}
if(r==null)
{
setTimeout(ModifyExportFileName,2000);
return;
}
else
{
var url=r.ExportUrlBase;
var i = url.indexOf("FileName=");
var j = url.indexOf("&",i+1);
var oldFileName= url.substring(i+9,j);
var filename=text.concat(year,month,day)
r.ExportUrlBase= url.substring(0,i) + 'FileName=' + filename+ url.substring(j);
}
//console.log(filename);
setTimeout(ModifyExportFileName,2000);
}
ModifyExportFileName();
I need date as a filename so date is added as "filename". you can change it as required

Resources