Delete all but x most resent files in a folder Google script - javascript

I have a folder where I store backup files and I want to keep only the 5 most recent files
All files are in a folder called New Project Backups
All files have New Project as part of their name
I found this here
Delete old files
How do I focus the Function to look in only the folder New Project Backups
Thanks
function myFunction() {
var file_iterator = DriveApp.getFiles();
var file_list = [];
while (file_iterator.hasNext()) {
var fl = file_iterator.next();
if (fl.getName().match("New Project"))
file_list.push(fl);
}
// Sort the files on date created
file_list = file_list.sort(function(fl1, fl2) {
return fl1.getDateCreated() < fl2.getDateCreated();
});
// Removing uneeded file
while (file_list.length > 5) {
var fl = file_list.pop();
// fl.setTrashed(true); // if you want it in the trash
// instead of fully removed.
DriveApp.removeFile(fl);
}
}

Using DriveApp.getFiles() will get you all files in the drive. you can fix that by replacing
var file_iterator = DriveApp.getFiles();
with
id = "0XrUxpDX-E8dpeE9EQmpYLeplOLB";
var folders = DriveApp.getFolderById(id);
var file_iterator = folders.getFiles();
the id is the folder id you want to work with, you can find it from the folder URL
Example,
Folder URL: https://drive.google.com/drive/u/1/folders/0XrUxpDX-E8dpeE9EQmpYLeplOLB
Folder ID: 0XrUxpDX-E8dpeE9EQmpYLeplOLB
enjoy ;)

Related

Java Script to get/combine data from multiple Google Sheets that are stored in different folders (archives)

I am trying a script to scrape data form a given Sheetname and a given range into 1 main sheet. the problem in this case is that the Spreadsheets (with multiple sheets) are archived in different folders. so I have 1 main folder and in that folder I have archive folders for every year (2012-2022).
I have made script that is going through these folders and get the folder Id's that part is working.
I also have made a script to get the data from the sheet ("Rekenblad") and the range "A11:AY136". I think that also should work.
The part where I connect those 2 function is going wrong. What I would recieve is:
A main file (The script is inside the main file) with:
A sheet (blad1) with a list of all the information of the file
A sheet (blad2) with all data ranges combined. Every time I run this script the data needs to be cleared so I dont have doubles.
The most important is point 2. point 1 is just for me to check if all files are imported correctly and a link so I can easily check those files.
Script looks like this:
function listFolders(folder) {
var sheet = SpreadsheetApp.getActiveSheet().clearContents();
sheet.appendRow(["Name", "URL","ssId", "Type"]);
var folder = DriveApp.getFolderById("FOLDER_ID_PARENT_FOLDER");
var subfolders = folder.getFolders();
while (subfolders.hasNext()) {
//Logger.log(folder);
var name = subfolders.next();
while (subfolders.hasNext()) {
//Logger.log(folder);
var name = subfolders.next();
var files = name.getFiles();
var cnt = 0;
var file;
var ssID
var fileType
var combinedData = []
while (files.hasNext()) {
var file = files.next();
cnt++;
Logger.log(file);
Logger.log(cnt);
data = [
file.getName(),
file.getUrl(),
ssID = file.getId(),
fileType = file.getMimeType(),
];
sheet.appendRow(data);
if (fileType ==="application/vnd.google-apps.spreadsheet"){
ssID = files.getId();
data = GetData(ssID)
data = data.map(function(r){return r.concat([file.getName()]);});
combinedData = combinedData.concat(data);
}
}
var wss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Blad1") ;
ws.getRange("A2:AY").clearContent();
wss.getRange(2, 1, combinedData.length, combinedData[0].length).setValues(combinedData);
}
}
}
function GetData(ssID){
var aa = SpreadsheetApp.openById(ssID);
var wa = aa.getSheetByName("Rekenblad");
var info = wa.getRange("A11:AY136").getValues();
return info
}

Google Script - Compare part of a file name to a subfolders name and move file to subfolder if there is a match

Thanks to the awesome people on here I have a script that is cross checking file names with folder names and moving the file to the folder if the name matches (code below)
What I'm struggling with now if searching the subfolder of a certain folder and checking the files to see if part of the name matches the subfolder name
e.g
Folders:
Folder name: example1
Subfolder name: example1-commercial
Subfolder name: example1-clients
Files:
example1-commercial.pdf (move to example1-commercial folder)
example1-clients.pdf (move to example1-clients folder)
Any help would be greatly appreciated!
Thanks!
function folderAndFiles(){
var files = [];
var folderMap = {};
var foldersParent = DriveApp.getFoldersByName("names").next();
var filesParent = DriveApp.getFoldersByName("files").next();
var filesIterator = filesParent.getFiles();
var foldersIterator = foldersParent.getFolders();
while(filesIterator.hasNext()) {
var currentFile = filesIterator.next();
files.push(currentFile);
}
while(foldersIterator.hasNext()) {
var currentFolder = foldersIterator.next();
folderMap[currentFolder.getName()] = currentFolder;
}
for (var i=0; i<files.length; i++) {
var file = files[i];
var fileName = file.getName().replace('.jpg', '');
var destinationFolder = folderMap[fileName];
if (destinationFolder) {
destinationFolder.addFile(files[i]);
filesParent.removeFile(file);
Logger.log("Moved");
}
}
}
You can use the following code to accomplish your goals:
function sortFiles() {
// var folders = Drive.Files.list({
// "q": "mimeType = 'application/vnd.google-apps.folder' and trashed = false",
// "fields": "items(title, id)"
// });
var folders = DriveApp.getFolders();
// var files = Drive.Files.list({
// "q": "mimeType != 'application/vnd.google-apps.folder' and trashed = false",
// "fields": "items(title, id)"
// });
var files = DriveApp.getFiles();
var folderIDs = [];
var folderNames = [];
var fileIDs = [];
var fileNames = [];
do {
var folder = folders.next();
folderNames.push(folder.getName());
folderIDs.push(folder.getId());
} while (folders.hasNext());
do {
var file = files.next();
fileNames.push(file.getName());
fileIDs.push(file.getId());
} while (files.hasNext());
for (var i = 0; i < fileNames.length; i++) {
for (var j = 0; j < folderNames.length; j++) {
if (folderNames[j].search(fileNames[i]) > -1) {
var oldFileParents = DriveApp.getFileById(fileIDs[i]).getParents();
DriveApp.getFolderById(folderIDs[j]).addFile(DriveApp.getFileById(
fileIDs[i]));
if (oldFileParents.hasNext()) {
do {
oldFileParents.next().removeFile(DriveApp.getFileById(fileIDs[i]));
} while (oldFileParents.hasNext());
}
}
}
}
}
Based on your comment I have updated the code to only use the DriveApp class and no Drive API. For future reference, I have commented the API calls to the method Files.list that I used to gather every file and folder (except the ones on the recycle bin).
The code will first use the methods .getFolders() and .getFiles() to gather all the folders and files of your Drive. It will later create two arrays per folders and files: one for IDs and other for names. Then, the names array are iterated looking for coincidences. After one coincidence is found, it will record the current folder(s) of the file with the methods .getFileById().getParents(). We need to use this approach because a single file can be inside different folders of Drive.
So the final steps are going to be: first, gather the current folder(s) of the file. After that, we shall include the file into the new folder. And finally, we must delete the parent(s) folder previously saved on the first step.
Please, write back to me again if you need further help or clarifications.

Google app scripts How do I move several files into a folder?

Anyone can help me? I need move several files. so What i do is find the files by name. but When i use getfilebyName the type is file interator, i cant make copy on that.
the code following is worked but I dun know how to do on several files
function copyAndMove(files,folder){
var files = DriveApp.getFileById('16QnYGb19tlCDu18KNwYPZkNgtE4T2ElK3Q_djI-hF64');
var folder=DriveApp.getFolderById('0B6ZorjJGEpzgOFFQdF9yT24zc2s');
var newfile = files.makeCopy('copy of '+ files.getName(), folder);
DriveApp.removeFile(files);
You can use your Iterator by using the statement below:
while (files.hasNext()) {
var file = files.next();
// do stuff with the file
}
For example, this code allow you to move the content from one folder to another one:
function moveFiles(source_folder, dest_folder) {
var files = source_folder.getFiles();
while (files.hasNext()) {
var file = files.next();
dest_folder.addFile(file);
source_folder.removeFile(file);
}
}
Source : ctrlq.org
Edit: You can move file by names. This function will get file by name, remove them from their actual location and put them on the dest_folder:
function moveFiles(string_name, dest_folder) {
var files = DriveApp.getFilesByName(string_name);
while (files.hasNext()) {
var file = files.next();
var parents = file.getParents();
while (parents.hasNext()) {
var parent = parents.next();
parent.removeFile(file);
}
dest_folder.addFile(file);
}
}

Is it possible to drop the copies into a predefined folder as opposed to the root

My company is using a google script to backup important files in google drive every day. The script makes an exact copy of the folder and subfolders and places to copy in the root of the drive. My question is: Is it possible to drop the copies into a predefined folder as opposed to the root.
function start() {
var sourceFolder = "original";
var targetFolder = "backup";
var source = DriveApp.getFoldersByName(sourceFolder);
var target = DriveApp.createFolder(targetFolder);
if (source.hasNext()) {
copyFolder(source.next(), target);
}
}
function copyFolder(source, target) {
var folders = source.getFolders();
var files = source.getFiles();
while(files.hasNext()) {
var file = files.next();
file.makeCopy(file.getName(), target);
}
while(folders.hasNext()) {
var subFolder = folders.next();
var folderName = subFolder.getName();
var targetFolder = target.addFolder(folderName);
copyFolder(subFolder, targetFolder);
}
}
Since the folder is predefined you have its folder id so you can use:
var predefined = DriveApp.getFolderById(id);
then change target to:
var target = predefined.createFolder(targetFolder)

migrate from DocsList to DriveApp

I'm new to google scripts and was able to manipulate some code to work for a project, but it will no longer work as a result of the following:
ReferenceError: "DocsList" is not defined.Dismiss
Here is the code I have:
function report() {
var folder = DocsList.getFolder("FOLDER NAME HERE");
var contents = folder.getFiles();
var file;
var data;
var sheet = SpreadsheetApp.getActiveSheet();
sheet.clearContents();
sheet.appendRow(["URL", "Employer"]);
for (var i = 0; i < contents.length; i++) {
file = contents[i];
var qaDate,qaERName
if (file.getFileType()==DocsList.FileType.SPREADSHEET) {
var dataSheet = SpreadsheetApp.open(file).getSheetByName("data");
var configSheet = SpreadsheetApp.open(file).getSheetByName("Config");
I have a few references to DocsList, I've done some digging and cant figure out how to get something similar to getfolder
Let's start with the first line:
var folder = DocsList.getFolder("FOLDER NAME HERE");
If you go to the documentation, and look at all the methods for DriveApp that have anything to do with folders, you'll see four methods:
getFolderById(id)
getFolders()
getFoldersByName(name)
getRootFolder()
There is only one method that will get just one folder, getFolderById(id). If you are getting the same folder every time, and you can easily get the ID, then use that option. If that is not possible, then you can use getFoldersByName(name), but that gets multiple folders. Even though it gets multiple folders, you can easily get just the first folder.
var folders = DriveApp.getFoldersByName('Folder Name');
var folder = folders.next();
Logger.log('folder: ' + folder.getName());
So, start there, and make that change.

Categories

Resources