Search files in shared Google Drive [duplicate] - google-apps-script

I have some Google Apps script code that searchs for files and folders on TeamDrive.
The issue I am having is that if a file or folder is created by my colleague, when I run my script it can't find the file. If I create a file, and my colleague runs the script, the script can't find the file even though we both have access to view, edit and can see the files and folders in Drive. If one of us edits the file made by the other person, then it becomes visible from the search.
I ran into a similar problem with the Drive REST api when doing some android development. In Android when calling files().list(), It took my a while to find out that I had to set the following in order for my search to be successfull every single time.
.setSupportsTeamDrives(true)
.setIncludeTeamDriveItems(true)
.setCorpora("teamDrive")
.setTeamDriveId(myFolder.getTeamDriveId())
I assume I am running into the same issue with my apps script code.
//Create the N Google docs files
function CreateNFiles(){
var spreadsheet = SpreadsheetApp.getActive();
var Nmain = spreadsheet.getSheetByName("Nmain")
var spreadsheetId = spreadsheet.getId();
var pdfDir = "Form Data";
var TemplatesFolder = null;
//Check and see if there is a 'Form Data' folder
var NFolderId = null;
var RFolderId = DriveApp.getFileById(spreadsheetId).getParents().next().getId();
var files = DriveApp.searchFolders('parents="'+RFolderId+'" and trashed=false');
while (files.hasNext()) {
var myfile = files.next();
if(myfile.getName() == pdfDir){
NOFolderId = myfile.getId();
}
}
https://developers.google.com/apps-script/reference/drive/drive-app#searchFiles(String)
this says to refer to
https://developers.google.com/drive/api/v3/search-parameters#examples_for_teamdriveslist
so I could potentially use
corpora="teamDrive"
is there a way to setSupportsTeamDrives? and setIncludeTeamDriveItems? and setTeamDriveId? in google apps scripts

Finding Files and Folders in a Team Drive
Here's a couple of functions I've been working on for my own needs. They're still a work in progress but one can file folders within a team drive folder and another can find items within a team drive folder. The Logger.log is setup to display item number, title, id, and mimeType.
This one finds Items (either files or folders). You can tell them apart by their types.
function findItemsInTeamDriveFolder(teamDriveId,folderId){
var teamDriveId=teamDriveId || '0AFN5OZjg48ZvUk9PVA';
var folderId=folderId || '1LK76CVE71fLputdFAN-zuL-HdRFDWBGv';
var options={
"corpora":"teamDrive",
"includeTeamDriveItems":true,
"orderBy":"folder",
"q":Utilities.formatString('\'%s\' in parents',folderId),
"supportsTeamDrives":true,
"teamDriveId":teamDriveId
};
var files=Drive.Files.list(options);
var data=JSON.parse(files);
for(var i=0;i<data.items.length;i++){
Logger.log('\nItem: %s - Title: %s - Id: %s - Type:%s - Trashed: %s\n',i+1,data.items[i].title,data.items[i].id,data.items[i].mimeType,data.items[i].explicitlyTrashed?'true':'false');
}
}
This one just finds folders in a folder. It's not reentrant it's a one level deal but currently that's all I need.
function findFoldersInATeamDriveFolder(teamDriveId,folderId){
var teamDriveId=teamDriveId || '0AAc6_2qyI7C0Uk9PVA';
var folderId=folderId || '1HenWOXTSCg96iAvA0ZkgEA9EGKlch4fz';
var optionalArgs={
"corpora":"teamDrive",
"includeTeamDriveItems":true,
"orderBy":"folder",
"q":Utilities.formatString('\'%s\' in parents and mimeType = \'application/vnd.google-apps.folder\'',folderId),
"supportsTeamDrives":true,
"teamDriveId":teamDriveId
}
var list=Drive.Files.list(optionalArgs)
var data=JSON.parse(list);
for(var i=0;i<data.items.length;i++){
Logger.log('\nItem: %s - Title: %s - Id: %s - Type: %s - Trashed;%s\n',i+1,data.items[i].title,data.items[i].id,data.items[i].mimeType,data.items[i].explicitlyTrashed?'true':'false');
findItemsInTeamDriveFolder(teamDriveId,data.items[i].id)
}
}
I thought that they might be helpful.
Meta Data for a file:
Search Parameters:
Drive.Files.List Documentation:

I just used Coopers code to list files that were in a shared drive. I added the code to find the teamdriveID. Two things that cost me some time and might be helpful for others: the number of files is restricted to 100 per default. So I changed it to 200 here. Also, the options file includes trashed files (very confusing) so I filtered them out with an if statement - I am sure this can be done more elegantly but this worked :)
var resource = {
'value': 'emailstring',
'type': 'user',
'role': 'writer'
}
var teamDriveId
// If you have several Team Drives, loop through and give access
var TeamDrive = Drive.Teamdrives.list();
for(var i = 0; i < TeamDrive.items.length; i++) {
if(TeamDrive.items[i].name == "foldernamestring") {
// This ID may also be a single file inside a Team Drive
teamDriveId = TeamDrive.items[i].id;
Logger.log("found "+TeamDrive.items[i].name);
}
}
var options={
"corpora":"teamDrive",
"maxResults":200,
"includeTeamDriveItems":true,
"supportsTeamDrives":true,
"teamDriveId":teamDriveId
};
var files=Drive.Files.list(options);
var data=JSON.parse(files);
var nritems= data.items.length
Logger.log("nritems "+nritems);
for(var i=0;i<nritems;i++){
if (data.items[i].explicitlyTrashed == false){
Logger.log('\nItem: %s - Title: %s - Id: %s - Type:%s - Trashed: %s\n',i+1,data.items[i].title,data.items[i].id,data.items[i].mimeType,data.items[i].explicitlyTrashed?'true':'false');
}
}

I use simple Apps Script code to search folders in a Shared Drive:
function searchFolderByTitle(title,ShDrId){
var folders = DriveApp.searchFolders("title contains '"+title+"' and '"+ShDrId+"' in parents");
while (folders.hasNext()) {
var folder = folders.next();
Logger.log(folder.getName());
}
}
You should use the operator "in" not "=" with "parents" parameter.

Related

Exporting folder information from Shared Drive; Issue with pageToken

I'm attempting to export the folder name, folder id, folder url, and filepath for folders within a Shared Drive. This part works, but I'm limited to 100 items. I'm attempting to use the pageToken/nextPageToken functionality to pull all items, but it doesn't seem to work and continues returning only 100 items. I'm using the same basic structure as google uses in their example code for this purpose and was also referencing this solution to a similar problem.
function getFolderURLs() {
var folders, pageToken;
var foldersArray = [["Folder Name", "Link", "Folder ID", "Filepath"]]
do {
try {
var optionalArgs = {
supportsAllDrives: true,
includeItemsFromAllDrives: true,
pageToken: pageToken,
maxResults: 100,
q: '"132vqY8oyd6xKpnxxxxxxxxxxx" in parents and trashed = false and mimeType = "application/vnd.google-apps.folder"'
}
var folders = Drive.Files.list(optionalArgs);
var allFolders = folders.items
if (!allFolders || allFolders.length === 0) {
Logger.log ('No folders found.');
return
}
for (i = 0; i < allFolders.length; i++) {
var folder = allFolders[i];
var name = folder.title
var link = folder.alternateLink
var id = folder.id
var parentID = Drive.Files.get(folder.id,{
supportsAllDrives: true,
}).parents[0].id
var parent = Drive.Files.get(parentID,{
supportsAllDrives: true,
includesItemsFromAllDrives: true,
}).title
var filepath = `${parent}/${name}`
foldersArray.push([name, link, id, filepath])
}
pageToken = folders.nextPageToken;
} catch (err) {
Logger.log('Failed with error %s', err.message);
}
}
while (pageToken);
var ss = SpreadsheetApp.create('Clients Folder ID Listing');
var sheet = ss.getActiveSheet();
sheet.getRange(1,1,foldersArray.length, 4).setValues(foldersArray)
Logger.log(foldersArray)
}
I believe your goal is as follows.
You want to retrieve the folder list in the specific folder.
The specific folder has multiple subfolders.
You want to achieve this using Google Apps Script.
When I saw your script, Drive.Files.get is used in a loop. In this case, the process cost might be high. And, in your script, it seems that the subfolders cannot be retrieved.
In this case, how about the following sample script? In this answer, I used a Google Apps Script library for retrieving the file and folder list using Google Apps Script. I created this library for like this situation.
Usage:
1. Install library.
Please install the Google Apps Script library. You can see the method for installing it at here.
2. Enable Drive API.
This script uses Drive API. So, please enable Drive API at Advanced Google services.
3. Sample script:
function myFunction() {
const folderId = "###"; // Please set the folder ID.
const obj = FilesApp.getAllFoldersInFolder(folderId);
if (obj.id.length == 0) return;
const foldersArray = [["Folder Name", "Link", "Folder ID", "Filepath"], ...obj.name.map((e, i) => {
const folderName = e.pop();
const folderId = obj.id[i].pop();
return [folderName, `https://drive.google.com/drive/folders/${folderId}`, folderId, e.join("/")];
})];
const sheet = SpreadsheetApp.create('Clients Folder ID Listing').getActiveSheet();
sheet.getRange(1, 1, foldersArray.length, 4).setValues(foldersArray);
}
When this script is run, the folder list is retrieved from the specific folder. In this case, the subfolders are included. And, the values of "Folder Name", "Link", "Folder ID", "Filepath" are put into the created Spreadsheet.
In this script, the folder list in the shared drive can be retrieved. When I tested this, I confirmed that a folder list including more than 100 folders could be retrieved.
Reference:
FilesApp: Google Apps Script library.

Google App Script timing out while removing Viewers, How to make the script more efficient?

I have a GAS that I run every month or so to remove Viewers and Editors from GoogleDocs and GoogleSheets that were created over 1 year ago. I have not found a way to return ONLY the documents which have the specific users I want to remove.
So the code is setup to loop thru all the documents in a specific folder and if the Viewers/Editors do not match the 2 owners, then it removes their access.
The problem is a few folders have a large number of files and it is timing out just reading thru to find out if any Viewers/Editors need to be removed.
Any ideas on how this code could be streamlined or if there is a way to query for only the documents not owned by a specific user?
var folder = folders.next(); //assume the match is the first one
folder = DriveApp.getFolderById(folder.getId()); //use the folderID of the year folder
processFolder(folder); //this starts in with the newest folder modified date under the Proposals/Year folder and works down thru the list until it times out after 5 minutes of running
function processFolder(folder) {
var asset;
var users;
var email;
var files = folder.getFiles();
var todaysDate = new Date();
while (files.hasNext()) {
var file = files.next();
var daysCreated = parseInt(((todaysDate - file.getDateCreated()) / 86400000)); //how many days since the document was created 24/3600/1000 = 86,400,000
if (daysCreated > RETENTION_DAYS) {
asset = DriveApp.getFileById(file.getId());
for (var i = 0; i < 2; i++) {
if (i == 0) {
users = asset.getEditors();
} else {
users = asset.getViewers();
}
for (var cnt = 0; cnt < users.length; cnt++) {
email = users[cnt].getEmail().toLowerCase();
if (email != "xxx1#gmail.com" && email != "xxx2#gmail.com") {
if (i == 0) { //Editors
asset.removeEditor(email);
} else { //Viewers
asset.removeViewer(email);
}
}
}
}
}
} //processFolder
About how this code could be streamlined or if there is a way to query for only the documents not owned by a specific user?, for example, if you want to retrieve only the files without including xxx1#gmail.com and xxx2#gmail.com as the writer and the viewer, how about using searchFiles instead of getFiles? When your script is modified, it becomes as follows.
Modified script:
function processFolder(folder) {
var emails = ["xxx1#gmail.com", "xxx2#gmail.com"]; // Please set the email addresses.
var query = emails.map(e => `not '${e}' in writers and not '${e}' in readers`).join(" and ") + " and trashed=false";
var files = folder.searchFiles(query);
var todaysDate = new Date();
while (files.hasNext()) {
var file = files.next();
var daysCreated = parseInt(((todaysDate - file.getDateCreated()) / 86400000));
if (daysCreated > RETENTION_DAYS) {
file.getEditors().forEach(e => file.removeEditor(e));
file.getViewers().forEach(e => file.removeViewer(e));
}
}
}
When this script is run, the writers and the viewers of the files without including "xxx1#gmail.com" and "xxx2#gmail.com" as the writer and the viewer are removed.
Note:
When this sample script is run, the writers and the viewers of the files without including "xxx1#gmail.com" and "xxx2#gmail.com" as the writer and the viewer are removed. So, I would like to recommend testing this script using the sample files. Please be careful about this.
Reference:
searchFiles(params)
Added:
From your replying, as another approach, in this case, how about the following sample script? In this sample, the following flow is used.
Retrieve all file IDs just under the specific folder using Drive API.
Retrieve permission IDs from the files using Drive API.
Create the requests for deleting the permissions except for "emails".
Delete permissions using Drive API.
Usage:
1. Install a Google Apps Script library.
In this sample, the batch request is used. In this case, I created a Google Apps Script library for this. So, please install the library. About the method for installing it, you can see it at here.
2. Enable Drive API.
This script uses Drive API. So, please enable Drive API at Advanced Google services.
3. Sample script:
Please copy and paste the following script to the script editor and set emails and folderId. And please run sample(). By this, the script is run.
function sample() {
var emails = ["xxx1#gmail.com", "xxx2#gmail.com"]; // Please set the email addresses.
var folderId = "###"; // Please set the folder ID.
// 1. Retrieve all file IDs just under the specific folder using Drive API.
var list = [];
var pageToken = "";
do {
var obj = Drive.Files.list({q: `'${folderId}' in parents`, maxResults: 1000, pageToken, fields: "items(id),nextPageToken"});
if (obj.items.length > 0) list = [...list, ...obj.items.map(({id}) => id)];
pageToken = obj.nextPageToken;
} while(pageToken);
// 2. Retrieve permission IDs from the files using Drive API.
var req1 = list.map(id => ({method: "GET", endpoint: `https://www.googleapis.com/drive/v3/files/${id}/permissions?pageSize=100&fields=permissions(id%2CemailAddress%2Crole)`}))
var token = ScriptApp.getOAuthToken();
var requests1 = {
batchPath: "batch/drive/v3", // batch path. This will be introduced in the near future.
requests: req1,
accessToken: token
};
var result1 = BatchRequest.EDo(requests1);
// 3. Create the requests for deleting the permissions except for "emails".
var req2 = list.reduce((ar, id, i) => {
var p = result1[i].permissions;
if (p.length > 0) {
p.forEach(e => {
if (e.role != "owner" && e.emailAddress && !emails.includes(e.emailAddress)) {
ar.push({method: "DELETE", endpoint: `https://www.googleapis.com/drive/v3/files/${id}/permissions/${e.id}`});
}
})
}
return ar;
}, []);
// 4. Delete permissions using Drive API.
var requests2 = {
batchPath: "batch/drive/v3",
requests: req2,
accessToken: token
};
var result2 = BatchRequest.EDo(requests2);
}
When this script is run, about all files just under the specific folder, all permissions except for the owner and emails are removed.
Note:
This script removes the permissions. Please be careful about this. So in this case, I would like to propose to test using a sample permitted files.
Reference:
BatchRequest

Trying to create tree-view of google drive folders

Many thanks for the comments and response. That code was a little too advanced for me and I ended up finding a very inelegant solution that I used because I ran out of time. I was able to get the code to list Folder and first level of subFolders with links, but I have not yet been able to get it to iterate through all levels of folders, mostly because I just need to back up and learn a lot of the basics. I was also able to get all folders to list using some code I found to create a tree, but I couldn't get it to format in a way that you could actually see the structure, or add links. I'm going to continue to try, and will post if I sort it out. Here is what I used, which was fine for our purposes because our shared drive is fairly limited.
For reference, this was the code I used to start with:
https://superuser.com/questions/1095578/list-of-subfolder-names-and-file-links-in-google-sheets-script
function listFolders(foldername) {
var ss = SpreadsheetApp.openById(ID);
var sheet = ss.getSheetByName("sheet name");
sheet.appendRow("Parent Folder", "Name", "Link" ]);
//change the folder ID below to reflect your folder's ID (look in the
URL when you're in your folder)
var folders = DriveApp.getFolderById(ID);
var contents = folders.getFolders();
var cnt = 0;
var folderD;
while (contents.hasNext()) {
var folderD = contents.next();
cnt++;
data = [
folders.getName(),
folderD.getName(),
folderD.getUrl(),
];
sheet.appendRow(data);
};
};
Original Post:
I am a beginner using script in google sheets and I am trying to create a list of folders in a google drive with many subfolders. Ideally it would be a tree form but I'd settle for a list at this point. I don't need to list all the files, just the folders. I have been trying to get the code below to work but it keeps hanging up at calling up the spreadsheet. Can anyone help?
I have tried calling up both the folders and the spreadsheet by both name and ID but it always tells me it can't execute the getactivespreadsheet command. I have also tried to modify the code referred to in another another question but I can't get that to work either: https://ctrlq.org/code/19923-google-drive-files-list
function generateFolderIndex(myfoldername) {
var folder = DriveApp.getFolderById('0B8vOJQUb-IIVTHdudlZSVkdtdE0');
var subFolders = folder.getFolders();
var childFolders = subFolders
var ss = SpreadsheetApp.getActiveSpreadsheet('1Trv9OtJFnD4AdSHrZKFfsSu6JMV9f78H6wwZNhF2_M4');
var sheet = ss.getSheetByName('Directory');
sheet.clear(directory);
sheet.appendRow([name, link]);
while (subFolders.hasNext())
{
var childFolder = childFolders.next();
var foldername = childFolder.getname();
var name = childFolder.getName()
var link = childFolder.getUrl()
var date = childFolder.getDateCreated()
data = [name, link]
sheet.appendRow(data);
}
};
I am trying to get a sheet that lists folders and subfolders with URL links. I am currently receiving the following error message:
[19-05-31 15:32:20:911 EDT] Execution failed: Cannot find method getActiveSpreadsheet(string). (line 5, file "Code") [0.432 seconds total runtime]
Or.. the easy way...
Use DRIVE or FS DRIVE APP for desktop in PC. Usea A CMD (windows)... AND THE FUNCTION
TREE >a.txt
The generated file a.txt will display all the tree.
IT SAVES HOURS OF RESEARCH.
SpreadsheetApp.getActiveSpreadsheet() doesn't have any parameters.
However
SpreadsheetApp.openById('ssid') does require and id. I think perhaps you meant to be using openById();
openById
getActiveSpreadsheet
This is a script that I'm currently working on but it generates a list of Spreadsheets and you can exclude folders by id and files by id.
function getAllSpreadsheets() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('FilesAndFolders');
if(sh.getLastRow()>0) {
sh.getRange(1,1,sh.getLastRow(),2).clear().clearDataValidations();
}
getFnF();
SpreadsheetApp.getUi().alert('Process Complete')
}
var level=0;
function getFnF(folder) {
var folder= folder || DriveApp.getRootFolder();
//var folder=DriveApp.getRootFolder();
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('FilesAndFolders');
var files=folder.getFilesByType(MimeType.GOOGLE_SHEETS)
while(files.hasNext()) {
var file=files.next();
if(isExcluded(file.getId(),'file')){continue;}
var firg=sh.getRange(sh.getLastRow() + 1,level + 1);
firg.setValue(Utilities.formatString('=HYPERLINK("%s","%s")',file.getUrl(),'FILE: ' + file.getName()));
firg.offset(0,1).insertCheckboxes('Exclude','Include');
}
var subfolders=folder.getFolders()
while(subfolders.hasNext()) {
var subfolder=subfolders.next();
if(isExcluded(subfolder.getId(),'folder')){continue;}
var forg=sh.getRange(sh.getLastRow() + 1,level + 1);
forg.setValue(Utilities.formatString('=HYPERLINK("%s","%s")',subfolder.getUrl(),'FOLDER: ' + subfolder.getName()));
//forg.offset(0,1).insertCheckboxes('Exclude','Include');
//level++;
getFnF(subfolder);
}
//level--;
}
function isExcluded(id,type) {//type: file or folder
var type=type||'Missing Input';
var xFldrIdA=['Excluded folder ids'];
var xFileIdA=['Excluded file ids'];
var type=type.toLowerCase();
switch(type) {
case 'file':
return xFileIdA.indexOf(id)>-1;
break;
case 'folder':
return xFldrIdA.indexOf(id)>-1;
break;
default:
throw(Utilities.formatString('Error: Invalid Type: %s in isExcluded.',type));
return true;//assume excluded
break;
}
}
Your welcome to use it, perhaps it will help.

"Can't find the insertSheet function" error after updating code to use advanced google services

I have just updated my script to use the new advanced google services. In this case i have inserted a file in a folder, and now i need to format the file: insert sheets, change colors, etc.
I am having problems for working the file because after using this service I cannot get the file to work with it, i get this error:
"Can't find the insertSheet function in the object FileIterator".
If you can head me to a place where I can find a solution, it would be very helpful.
This is the code i am using:
function HAR() {
//This is the new part of the code...
var name = "Template";
var folder = DriveApp.createFolder("HAR");
var folder_id = folder.getId();
var resource = {
title: name,
mimeType: MimeType.GOOGLE_SHEETS,
parents: [{ id: folder_id }]
}
var fileJson = Drive.Files.insert(resource);
var File_id = fileJson.id;
var Template = DriveApp.getFilesByName("Template");// I guess this is not working
//This is the old part of the code...
const ssNames = ["California","Arizona","Florida","Los Angeles"];
const states = ssNames.length;
var x;
for (x = 0; x < sNames.length; x++){
Template.insertSheet(sNames[x]); //I can't manage to insert the sheets
}
Template.getSheetByName("Sheet 1").activate();
Template.deleteActiveSheet();
}
Template is a FileIterator. So it's been assigned a value, but your code doesn't show Template as being assigned a value, so you must have other code that you haven't shown.
FileIterator only has 3 methods available to it:
getContinuationToken()
hasNext()
next()
You probably want to insert a sheet into the newly created spreadsheet file.
var File_id = fileJson.getId();
var newSS_file = SpreadsheetApp.openById(File_id);

CryptoLocker - restore Drive file version with Google Apps Scripts

long story short I got infected by the CryptoLocker Virus. My “normal” local files are not the problem because these files I backup. But I was using the Google Drive Sync client and all my Drive files got encrypted. I didn’t back them up because I thought Google Drive is save and my data is stored all over the world (my fault I know).
Now I can see that Google Drive provides versioning. This means my old uploads are still on the server. I can restore the previous version file by file but by several thousand files, good luck.
I contacted the Google G Suite support team (I’m using Google G Suite for my business) and asked them if they can restore the latest version in one bulk action. The answer was “no you have to do it file by file”. Therefore I was checking the internet for scripts, tools etc.
I found a Google Apps Script in the Google Drive help forum “https://productforums.google.com/forum/#!topic/drive/p08UBFYgFs0https://productforums.google.com/forum/#!topic/drive/p08UBFYgFs0”.
1) I added the “Google Apps Script” app to my drive.
2) I created a new app and past the script:
function testSmallFolder() {
var smallFolder = DriveApp.getFolderById('FOLDER_ID_HERE');
var files = smallFolder.getFiles();
while (files.hasNext())
{
file = files.next();
deleteRevisions(file);
}
var childFolders = smallFolder.getFolders();
while(childFolders.hasNext())
{
var childFolder = childFolders.next();
Logger.log(childFolder.getName());
var files = childFolder.getFiles();
while (files.hasNext())
{
file = files.next();
deleteRevisions(file);
}
getSubFoldersAndDelete(childFolder);
}
}
function deleteRevisions(file)
{
var fileId = file.getId();
var revisions = Drive.Revisions.list(fileId);
if (revisions.items && revisions.items.length > 1)
{
for (var i = 0; i < revisions.items.length; i++)
{
var revision = revisions.items[i];
var date = new Date(revision.modifiedDate);
var startDate = new Date();
var endDate = new Date(revision.modifiedDate);
var fileName = Drive.Files.get(fileId);
if(revision.modifiedDate > "2017-02-16T10:00:00" && revision.modifiedDate < "2017-02-18T10:00:00" && revision.lastModifyingUserName == "ENTER_MODIFIED_USERNAME_HERE]]" && file.getName() !== "HELP_DECRYPT.URL" && file.getName() !== "HELP_DECRYPT.PNG" && file.getName() !== "HELP_DECRYPT.HTML")
{
Logger.log(' %s, Date: %s, File size (bytes): %s',file.getName(),
date.toLocaleString(),
revision.fileSize);
return Drive.Revisions.remove( fileId, revision.id);
}
}
} else
{
Logger.log('No revisions found.');
}
}function getSubFoldersAndDelete(parent)
{
parent = parent.getId();
var childFolders = DriveApp.getFolderById(parent).getFolders();
while(childFolders.hasNext())
{
var childFolder = childFolders.next();
var files = childFolder.getFiles();
while (files.hasNext())
{
file = files.next();
deleteRevisions(file);
}
getSubFoldersAndDelete(childFolder);
}
return;
}
3) The script provides 3 functions “testSmallFolder” / “deleteRevisions” / “getSubFoldersAndDelete”. Looks like the function “festSmallFolder” can just work on a certain folder. Line 2: FOLDER_ID_HERE
4) I created a folder and moved my files into this folder. Afterwards I got the folder ID (URL) and added it to the script.
5) In line 37 you can add the start and end date of the modification. I also adjusted the username in the same line.
6) I saved the script and ran the “testSmallFolder” function.
7) I get an error message: “ReferenceError: "Drive" is not defined. (line 27, file "Code")“.
Line 27 looks like this: „var revisions = Drive.Revisions.list(fileId);”.
I contacted again the Google G Suite support and asked them for help regarding this error. Their answer was “Sorry we do not support scripts.”
Now I’m here guys and asking you for help. Maybe we can get this script running so that I can restore the latest working version of my files.
I really appreciate any help you can provide.
You first of all must be sure to enable Advance Drive Service as documented here:
https://developers.google.com/apps-script/advanced/drive
Go in your script page, click on Resources --> then click on Google Advances Services, then enable (must be GREEN!) Drive API.
Maybe an alert open you a page where you MUST abilitate the script to access at your drive and folders (I think only the first time).
After do that, if you put a breakpoint on the 2nd row of the script and run the debugger istruction after istruction, you pass the 27 line without any problem, and you can see in the variable stack all the string for the first file, then for the second etc....
Stop then and Run normally this time and all will be ok.
Have a good night.
Have a look at https://gitlab.com/strider/delockyfier . This is a single page app in JavaScript which you could probably run as is, or easily convert to Apps Script if that's where you would prefer to run it from.