DriveApp.getFoldersByName give different result depending on user - google-apps-script

I have a script that copies folders and content. It gets the folder names to copy from a sheet. All this works.
When the script comes to
DriveApp.getFoldersByName("NameOfFolder");
The script finds the folder iterator when I execute the script, but not when my colleague does.
If he does a search in Drive he can see the folder, the script returns null.
We have the same access to the folder. Its a shared folder on Google Drive.
Can anyone explain?
Here is the code that reproduces the error:
NB: the sheet supplies the script with propper names of folders to look for.
function shortTest() {
var episodeFolderList = DriveApp.getFoldersByName("Folder name");
var episodeFolderByID = DriveApp.getFolderById("longFolderIDXXXXXXX");
Logger.log(episodeFolderByID+"-By ID")
var episodeFolder=episodeFolderList.next();
Logger.log (episodeFolder+ " -by name")
}
Ill ask him to log out of other accounts and try again.
Thank you for all the input.

Related

google script openByUrl autorization, trigger activation

I'm quite new to programming and struggling with apps authorization :
I created a code that has to access other files of my Gdrive, with the command openByUrl, which sends back an error message, telling me it doesn't have the authorization to perform openByUrl.
I went through the oauth2 scopes but can't understand how to give the authorization to my script.
I already have an internet copied script that runs DriveApp.getFolderById, but it runs through a menu.
I want both getFolderById and openByUrl to run on a trigger (each day at midnight) thus, it can't run through a menu.
The goal of my script is to list all files in a specified folder, get the spreadsheet ones, and extract specific cells from these spreadsheets.
I got something running with importance, but clearly, it's too bulky to run properly on more than 3000 files.
Could anyone explain to me how to give authorizations to openByUrl please? (even better if in French ;-) )
Many thanks in advance for your help.
Answer
I would create a new project and copy the whole code.
If you want to check why in a particular project you have this error, you can open the manifest file that has the required scopes. You can find it clicking on Project Settings on the left bar and then Show "appsscript.json" manifest file in editor. The field oauthScopes has to contain all the required scopes or has to be deleted.
Methods explanation:
DriveApp.getFoldersByName(name) get all the folders with a specified name. Take the first one with .next()
Folder.getFilesByType get all the files with a specific mimetype
SpreadsheetApp.openById open a specific Spreadsheet document
Spreadsheet.getSheets() get all the sheets in an array
Sheet.getRange() get a specific range
Range.getValues() get the values of a specified range
Updated code:
function main() {
var folderName = 'folder'
var type = MimeType.GOOGLE_SHEETS
var folders = DriveApp.getFoldersByName(folderName).next().getFolders()
while (folders.hasNext()) {
var folder = folders.next()
console.log(folder.getName())
var files = folder.getFilesByType(type)
while (files.hasNext()) {
var file = files.next()
console.log(file.getName() + ': ' + file.getid())
var sheets = SpreadsheetApp.openById(file.getid()).getSheets()
var values = sheets[0].getRange('A1:B2').getValues()
console.log(values)
}
}
}

Problem with permissions when saving a copy of a spreadsheet to a shared folder

This is the first time I have posted so please excuse any breaches of etiquette!
I have developed a spreadsheet for our business to use when cashing up tills with some basic scripts to add functionality. One of these allows the user to 'submit' the cashing up by saving a copy of the spreadsheet in a shared folder renamed with the date the user was working on. The script then clears the contents of the unprotected ranges ready to be used again. I am the owner of both the spreadsheet and the folder, but I have shared both to the users with 'editor' permissions.
My problem is when they come to run the script that submits the cashing up, it gives an exception that states
You do not have permission to access the requested document".
When I run the script myself it works as planned.
Here is the script
//Function to set filename and copy to archive
function nameAndArchive() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var newfilename = ss.getSheetByName('Calculations').getRange(4, 3).getDisplayValue();
var destFolder = DriveApp.getFolderById('1GVlutqUFOEWGmeqEdQU8v7J4DZh9fZ1J');
DriveApp.getFileById(ss.getId()).makeCopy(newfilename, destFolder);
}
I can't figure out how I can change the permissions to get the script to function as intended. Any help would be gratefully received!

Can I add a script to a Google Sheet using another script?

I have a script populate() to run an automation script on Google Sheets. I want this script to be run on over a hundred Google Sheets files. Is there a way to write a script to add to (or at least run) my populate() script on all those files? I prefer to be able to add the script to each file because we may need to run the scripts multiple times for each file. Otherwise, I will have to manually copy/paste the script to each sheet, which takes time.
Update: Removed the part about converting Excel files to Google Sheets because I found the answer for that on another thread here.
Solution
From what I have understood from your post, your question is about how to convert a series of Excel files inside a Drive folder into Google Sheets to then execute a function in them.
For that, you could iterate over all the files of your folder and convert them with the use of Drive.insert from the Drive API. For that, you will have to enable in your script the Advanced Google Services. If you do not know how to do so, please follow these indications.
The follow script performs what I think you are aiming for, it has self explanatory comments:
function convertExcelToGoogleSheets() {
// Id of the folder where you have all your excel files
var folderId = 'FOLDERID';
var folder = DriveApp.getFolderById(folderId);
// Get all the files in your folder and iterate over them
var files = folder.getFiles();
// For each file:
while (files.hasNext()){
var file = files.next();
// Get its blob (content)
var blob = file.getBlob();
// Create the resource to insert the Google Sheet file. Put the same name
// as the original and set the type of the file to Google sheets and its
// parent folder to where the excel files are located
var resource = {
title: file.getName(),
mimeType: MimeType.GOOGLE_SHEETS,
parents: [{id: folderId}],
};
// User Drive API to insert the actual file and get its ID
var id = Drive.Files.insert(resource, blob).getId();
// Whatever function you want to perform in the newly created Google Sheet
// pasing the parameter of the file id
myScript(id);
}
}
// Set the first cell of all the converted sheets to "IT WORKED"
function myScript(id){
SpreadsheetApp.openById(id).getActiveSheet().getRange('A1').setValue('IT WORKED!');
}
EDIT: If you want to run a script for each of this converted sheets you can simply call it in the while loop and pass the new file id as a parameter to then be able to use the script (remember to encapsulate this script in a function).
I hope this has helped you. Let me know if you need anything else or if you did not understood something. :)

Google Sheets - Script to “Replace” instead of “Create”, when file name is the same

EDIT to try and make this easier to understand:
Here is what I did:
I created a Google Spreadsheet. I created a SCRIPT that saves it to a Google Drive Folder using a File Name based on the date of service and Customer Name.
This is the Script I currently have:
// This creates a custom Menu Function so that I can save the file.
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Choice Menu')
.addItem('Submit Form','saveAsSpreadsheet')
.addToUi(); }
// Saves Spreadsheet in Google Drive Folder
function saveAsSpreadsheet() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var destFolder = DriveApp.getFolderById("0B8xnkPYxGFbUMktOWm14TVA3Yjg");
DriveApp.getFileById(sheet.getId()).makeCopy(getFilename(), destFolder);
}
//This Function uses a cell "G4" (Which is Date and Customer Name) to create a file name. This file name will be then used for the above Script.
function getFilename() {
var spreadsheet = SpreadsheetApp.getActive();
var sheet = spreadsheet.getSheetByName('Manifest');
var cell = sheet.getRange('G4');
var filename = cell.getValue();
return filename;}
So My code works GREAT except for one Problem.
Here is my Problem:
When I Save the Spreadsheet a 2nd time using the above Script, it saves a new file. I want to save it as a new file unless the Filename is the same. IF the file name is the same, I want to delete the original file, and then save the new file.
What I tried:
From what I understand reading the comments below, I need to run a code that "1. will need to run a query to see if any files exist with your chosen name, and then act accordingly. 2. If there are no files with that name, then go ahead and create one (using the function I listed above). If there is a file with the same name, 3. delete the original file and create a new one with the same name.
I tried for several days coming trying different options, and none of it worked, so I am looking to start over.
Appreciate any coding solutions or direction on where to go!
Your script is the container-bound script of Spreadsheet.
When the Spreadsheet with the searched filename is existing in a specific folder, you want to replace it to the active Spreadsheet.
In the current stage, a file cannot be replaced while the file ID is not changed. So in this modified script, the active Spreadsheet is copied and the searched file is deleted.
When the searched file is not existing in a specific folder, you want to copy the active Spreadsheet to the folder.
You want to use the value returned from getFilename() as the filename.
If my understanding is correct, how about this modification? I think that there are several solutions for your situation. So please think of this as just one of them.
Modified script:
Please modify saveAsSpreadsheet() as follows.
function saveAsSpreadsheet() {
var folderId = "0B8xnkPYxGFbUMktOWm14TVA3Yjg";
var folder = DriveApp.getFolderById(folderId);
var files = folder.getFilesByName(getFilename());
if (files.hasNext()) {
files.next().setTrashed(true);
}
var sheet = SpreadsheetApp.getActiveSpreadsheet();
DriveApp.getFileById(sheet.getId()).makeCopy(getFilename(), folder);
}
Note:
In order to search the file, I used getFilesByName() because I thought the filename seems constant.
setTrashed() for removing the file is used for this script. In this case, the file is put in the trash box. If you want to directly delete the file, you can achieve it using Drive API. At that time, please tell me.
References:
getFilesByName()
setTrashed()
Edit:
If you want to directly delete the file, please modify the script as follows.
From:
files.next().setTrashed(true);
To:
var params = {method: "delete", headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()}};
UrlFetchApp.fetch("https://www.googleapis.com/drive/v3/files/" + files.next().getId(), params);
I used the method using UrlFetchApp because I thought that in your situation, Drive API has already been enabled. In this case, you can use the delete method of Drive API by only replacing the script.
Reference:
delete method of Drive API
You need to take a step back and change your thinking about filenames.
In GDrive, files are identified by their unique ID. The name is just a metadata property alongside timeModified, owner, mimeType, etc. So having multiple files with the same name is as natural as having multiple files with the same mimeType.
Your code will need to run a query to see if any files exist with your chosen name, and then act accordingly. If there are no files with that name, then go ahead and create one. If there are, then you have the choice to update the existing file, or delete the original file(s) and create a new one with the same name.

Google Drive Service. Copied file to group drive folder. File is blank

I'm having an issue with the file handling of a Google Sheet that is produced from another Google Sheet when I run a google apps script. When I run the script, a new output file is produced and sent to folders with a specific label. The goal is to have the output file added to a specific folder in a group drive. The script and files regarding my problem all reside on the group drive too fyi.
When I run the script this is what happens.
A file is created within my personal Google Drive because I have a folder with the same exact name as the one on the group drive (this was my test environment for the script). This file on my drive has all the desired output within the Google Sheet. A file was also being added to the root of my drive, but the script now removes it from the root.
A file is created on the group drive, but it is completely empty. The file is correctly named, but there are no contents within the actual spreadsheet.
Here is the script that is handling the output file:
var sourceFilename = ss.getName();
var splitSourceFilename = sourceFilename.split("LMS");
var targetFilename = splitSourceFilename[0] + "Allowed_Layers_Vx";
// move the new spreadsheet to Allowed Layers Lists folder
var folders = DriveApp.getFoldersByName("Allowed Layers Lists");
while (folders.hasNext()) {
var folder = folders.next();
var ssNew = SpreadsheetApp.create(targetFilename);
var copyFile = DriveApp.getFileById(ssNew.getId());
folder.addFile(copyFile);
DriveApp.getRootFolder().removeFile(copyFile);
}
Some other information about the Group Drive:
I did not create the Group Drive. It is shared with me
I am the owner of the folders in which the files and scripts reside.
I am the owner of all the files and scripts in these folders that I own too.
I have edit permissions at every level of this group drive.
there is nothing in your script above that actually does the "file copy". It just creating new empty file with SpreadsheetApp.create(targetFilename) and adding that to the folder.
To make a copy of the Google Sheet, you may refer to the answer at Google App Script: How do I make copy of spreadsheet and save it to particular folder?
I ended up moving that block of code to the end of the script after the data processing occurs. For some reason, within my own drive, it didn't matter when I added the file to another folder, the script would still update all instances of that file. However, within a group drive, only the file within my own root was being updated (till I moved that block of code to the end of the script).
Any explanations on why this occurs is welcome.