Get Current Google Script Name to a Variable - google-apps-script

Does anyone know a way to get the name of the current google script file that's bound to the sheet you are using and write it to a variable? I want to put it into a sheets cell to keep track of changes I make.
Cheers

var id = ScriptApp.getScriptId();
var name = DriveApp.getFileById(id).getName();
Logger.log(name);

For standalone Google Scripts (not bound to any Google Sheet or Docs), you can use the DriveApp service to get the file name from Drive.
Right-click the file in Google Drive and copy the Share Link. Then get the ID from the shared link and use the DriveApp service to retrieve the name from the file ID.
function getName() {
var fileId = "123";
var file = DriveApp.getFileById(fileId);
return file.getName();
}

Related

Appscript to get hyperlink to another google sheet

I am looking for a code that will help me to find the hyperlink of another google sheet on my google drive, everything i have read explains how to get the link for the active sheet..
any ideas?
Thanks a lot
You need to use DriveApp with functions getFilesByName or getFilesByType. Then provide file id to SpreadsheetApp.openById.
This look will give you the hyperlink to every sheet in a spreadsheet
SpreadsheetApp.openById(file.getId()).getSheets().forEach(s =>
tree.txt.push([ `=HYPERLINK("https://docs.google.com/spreadsheets/d/${file.getId()}/edit#gid=${s.getSheetId()}","${s.getName()}")`]));
It generates a column. It's just a fragment of a piece of code
I have something a bit more simple to apply. The code below goes into the Drive folder and list down every file (doc/sheets/pdf etc) and its hyperlink.
All you will need to change is your tab name to store the folder details and your Gdrive folder ID.
If you want to extract folders within a folder in the future you can switch getFiles() to getFolders().
function folderitems(){
const ss=SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet 1'); //Edit tab name to list the folder details
const parentFolder=DriveApp.getFolderById('INPUT FOLDER ID HERE'); //Input Gdrive ID here
const contents=parentFolder.getFiles();
ss.appendRow(['name','link']);
while (contents.hasNext()){
var file = contents.next();
var name=file.getName();
var link=file.getUrl();
ss.appendRow([name,link]);
}
}
Outcome should look something like this.
To retrieve the URL of one spreadsheet by script
function getFileUrl() {
var nameOfFile = 'your file name'
var files = DriveApp.getFilesByName(nameOfFile);
while (files.hasNext()) {
var file = files.next();
console.log (file.getUrl())
}
}

google apps script. copy files to one drive

I would have files stored in google drive and I would like to copy (or move) those files to my OneDrive. I have managed to connect OneDrive to google drive and I can successfully create folders and upload files by file ID. I am trying to copy (or move) multiple files at once from google drive to OneDrive though without any luck yet. I am not good at programming just doing everything by tutorials only but yet could not find any working one. Maybe anyone could guide me how to do it? For the final idea I would like to achieve that files from google drive would be copied even to separate folders by the part of file title (name and surname, if to be exact). Currently I have "developed" such script:
function moveFiles(source, dest_folder) {
var source = DriveApp.getFolderById("1faFbaXJNziwIGyer2H2IPALQ8ahBfGMc");
var prop = PropertiesService.getScriptProperties();
var odapp = OnedriveApp.init(prop);
var files = DriveApp.getFiles();
while (files.hasNext()) {
var file = files.next();
var dest_folder =
OnedriveApp.init(PropertiesService.getScriptProperties()).uploadFile(files,
"/samplefolder");
}
}
I believe your current situation and your goal are as follows.
You are using OnedriveApp.
You have already been finished the authorization process. So you have already been had the access token and refresh token in the PropertiesServices.
You want to upload the files in a specific folder of Google Drive to a specific folder in OneDrive.
The number of files is 10 - 20.
The file size is small.
From your following reply
I have changed accordingly to: var files = file.getId(); but then I receive such error: TypeError: Cannot read property 'getId' of undefined moveFiles # srcpt.gs:5 If I use DriveApp.getFiles() or source.getFiles(), I receive such error: Exception: Unexpected error while getting the method or property getFileById on object DriveApp. convToMicrosoft # code.gs:629 OnedriveApp.uploadFile # code.gs:460 Appreciated for any help.
About var files = file.getId(); and If I use DriveApp.getFiles() or source.getFiles(), I receive such error:, unfortunately, I cannot understand it.
In this case, how about the following modification?
Modified script:
function myFunction() {
var prop = PropertiesService.getScriptProperties();
var odapp = OnedriveApp.init(prop);
var source = DriveApp.getFolderById("###"); // Please put your folder ID.
var files = source.getFiles();
while (files.hasNext()) {
var file = files.next();
odapp.uploadFile(file.getId(), "/samplefolder/"); // Please set the destination folder name. In this case, the folder name in OneDrive.
}
}
When "/samplefolder" is used, an error occurs. Please enclose the folder name by / like "/samplefolder/". Please be careful about this.
When this script is run, the files in the specific folder of Google Drive are copied to the destination folder of /samplefolder/ in OneDrive.
References:
OnedriveApp
getFolderById(id)
getFiles()

Google Forms Rename "File upload" File to "Question - Submitter"

I am using Google Forms to collect images from team members and I want to ensure that each file that is uploaded to Google Forms and saved in Google Drive has the same naming convention.
There are five File upload questions that team members are asked to upload their images to. The files are placed into Google Drive folders with random file names followed by - firstName lastName. On an onFormSubmit trigger I would like to change the names of the user-provided files to fileUploadQuestionName - firstName lastName.
I am pretty new to Google Apps Script and I have no idea how to go about doing this. Any help would be greatly appreciated!
You can change the name of the uploaded file on each form submit by the following process
retrieve the last form response onFormSubmit with form.getResponses()[LAST FORM SUBMISSION]
retrieve the ID of the uploaded file with getItemResponses()[QUESTION NUMBER].getResponse()
open the file ID with DriveApp and change its name as desired
function myFunction() {
var form=FormApp.getActiveForm();
// returns the total number of form submissions
var length=form.getResponses().length;
//replace QUESTION NUMBER through the index of the question prompting the file upload - keep in mind that the first question has the index 0
var id=form.getResponses()[length-1].getItemResponses()[QUESTION NUMBER].getResponse();
//getResponses()[length-1] retrieves the last form response, accounting for the fact that the first index is zero and hte last length-1
//gets the name of the question
var fileUploadQuestionName=form.getResponses()[length-1].getItemResponses()[QUESTION NUMBER].getItem().getTitle();
//accesses the uploaded file
var file=DriveApp.getFileById(id);
name = file.getName();
//changes the file name
var name = fileUploadQuestionName+' - '+name.split(' - ')[1]
file.setName(name);
}
PS: If you want to change a posteriori the names of all the files submitted and not just the last files - you need to loop through all form responses:
for(var i=0;i<length;i++){
var id=form.getResponses()[i].getItemResponses()[QUESTION NUMBER].getResponse();
...
...
}
The easiest way to do this would likely be by either iterating through the specified folder in google drive on a time-based trigger and either checking if they meet your specified condition or moving them to a different folder after they're renamed.
function checkFile()
{
var files = DriveApp.getFolderById('ID of Folder').getFiles();
// you can find this by going to form responses and clicking the link to an attached file and copying the id from the URL
// https://drive.google.com/drive/folders/xxxxxxxxxxxxxxxxxxxxxxxxxxx
var fileUploadQuestionName = 'Test';
while(files.hasNext())
{
var file = files.next();
var name = file.getName();
if(name.indexOf(fileUploadQuestionName) == -1)
{
name = fileUploadQuestionName+' - '+name.split('-')[1]
file.setName(name);
}
}
}
From there you'll need to add a time-based trigger to run every hour or day or minute depending on how critical it is to always find files of the correct name.
I can't find any documentation on accessing the file from within the response item on google's formApp documentation.

Insert Image into Spreadsheet Cell from Drive using Google Apps Script

I would like to be able to add an image file into my spreadsheet from Google Drive. I see there is a built-in image function available =image, but this requires a URL and that image files should be shared publicly on the internet. However, I am working with digital assets and can not share them publicly.
I have the following code, this works but does not add to the required cell. Is this at all possible?
function insertImageFromDrive(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var fileId = '0B5UAkV0avfiKNGYtd1VzUzlsTVk';
var img = DriveApp.getFileById(fileId).getBlob();
sheet.insertImage(img, 4, 3)
}
Try using the guide Insert image in a spreadsheet from App Script:
function insertImageOnSpreadsheet() {
var SPREADSHEET_URL = 'INSERT_SPREADSHEET_URL_HERE';
// Name of the specific sheet in the spreadsheet.
var SHEET_NAME = 'INSERT_SHEET_NAME_HERE';
var ss = SpreadsheetApp.openByUrl(SPREADSHEET_URL);
var sheet = ss.getSheetByName(SHEET_NAME);
var response = UrlFetchApp.fetch(
'https://developers.google.com/adwords/scripts/images/reports.png');
var binaryData = response.getContent();
// Insert the image in cell A1.
var blob = Utilities.newBlob(binaryData, 'image/png', 'MyImageName');
sheet.insertImage(blob, 1, 1);
}
Just replace the necessary values. The part where you indicate which cell you insert the image is in:
sheet.insertImage(blob, 1, 1);
There is a google spreadsheet add-on ImageKit to help insert multiple images from difference sources including Google Drive, check it out > https://chrome.google.com/webstore/detail/imagekit/cnhkaohfhpcdeomadgjonnahkkfoojoc
Here you find a screenshot of tool's interface.
It is not possible if the drive image file is not public on your google drive, Having said that there is a trick to overcome i.
First make sure the image file is temporary public on your drive. you can do that also via app script by changing the file permissions to DriveApp.Access.ANYONE, DriveApp.Permission.EDIT. Then the drive file is like a file as if it was from the internet. You can then add the blob.
After that you can decide two things.
Change the permissions back or remove the image file from your drive (if you only want to use it embedded in your blob (also via app script code if you want)
good luck
I don't think it is currently possible, see here: https://code.google.com/p/google-apps-script-issues/issues/detail?id=3303
Here's another alternative:
var fileId = "..."; // your image's google drive id
sheet.insertImage("https://docs.google.com/uc?id=" + fileId, column, row);
Just make sure your file has link sharing turned on (anyone with the link can view) otherwise this method won't work.
Documentation

How to fetch the ID of a Google Spread Sheet via Google Apps Script?

I've created one Google spread sheet and I want to find the ID of that spread sheet. I've tried too much to search on Google but could not succeed.
Please show me the way / script by that I can fetch the spreadsheet ID of an Active spread Sheet..
Thanks
The ID (key) of the spreadsheet is in the URL (the part between key= and #gid=). You can retrieve it with GAS using something like:
function getId() {
Browser.msgBox('Spreadsheet key: ' + SpreadsheetApp.getActiveSpreadsheet().getId());
}
Note, often you will get a totally different string with each method, but they both should work the same.
Remember that the getId() function from a Spreadsheet object returns a different id compared with getId() from File object, even if the File (that is managed from DriveApp) is the same spreadsheet.
Anyhow, if you open a file from DriveApp using the id provided by the Spreadsheet, you will obtain the correct File object, returning - with getId() - the "File" id, which is different from the one that you used to open the File.
It seems confusing, but it works so. I had some issues in some scripts coming from this "double" id for the same thing.
the sheet is is present in between the the
d
and
edit
of the spreadsheet url.
example -: if the sheet url is
https://docs.google.com/spreadsheets/d/1rV2_S2q5rcakOuHs2E1iLeKR2floRIozSytAt2iRXo8/edit#gid=0
the sheet id is
1rV2_S2q5rcakOuHs2E1iLeKR2floRIozSytAt2iRXo8
for more information go to google sheets api official documentation
Google App Script
To get the spreadsheet id of a spreadsheet in a specific folder:
function getSSID(){
let folderID = "the id of the folder to search in"
let folder = DriveApp.getFolderById(folderID);
let SSName = "the name of the spreadsheet to search for"
let allSSIDs = []; // empty array to hold the Id's of spreadsheets with the name SSName
let allMatching = folder.getFilesByName(SSName);
while(allMatching.hasNext()){
let ss = allMatching.next();
allSSIDs.push(ss.getId());
}
Logger.log(allSSIDs);
// array of all spreadsheet ids if the spreadsheet had the name we are looking for
// which hopefully there is only one that matches the exact spreadsheet name
}
To get the Current Spreadsheets ID:
function getCurrentSSID(){
let ssID = SpreadsheetApp.getActiveSpreadsheet().getId();
Logger.log(ssID);
}