I am trying to fetch the email ID of a user from the admin directory using his/her first name obtained from a spreadsheet, which simply checks if an email id exists in the directory and if yes shows his/her email id, here is my code:
function scanSsheet(){
var originalSpreadsheet = SpreadsheetApp.openById('xxxxxxxx-xxxxx-xxxxxxx-xxxx').getSheetByName("Form Responses 1");
var getRange = originalSpreadsheet.getDataRange();
var data = originalSpreadsheet.getDataRange().getValues();
for (var i = 1; i < data.length; i++) {
var volunteerFirstName = data[i][3];
var volunteerLastName = data[i][4];
Logger.log('****************Record No: ' + i + '****************');
Logger.log('volunteerFirstName: ' + data[i][3]);
Logger.log('volunteerLastName: ' + data[i][4]);
Logger.log('fetchUser is called');
var checkUser = fetchUser(volunteerFirstName);
if(checkUser){
Logger.log('Email exists');
}
else{
Logger.log('The user doesnot exist in the directory');
}
}
}
//Checks if the user exists in the directory or not and display email id if yes
function fetchUser(volunteerFirstName){
var isUser
try{
var email = AdminDirectory.Users.list({givenName: volunteerFirstName}); // This line should fetch email but it is not working
var user = AdminDirectory.Users.get(email);
Logger.log('email:' +email);
isUser = true;
} catch (e){
isUser = false;
}
return isUser;
}
As seen I have used var email = AdminDirectory.users.list({givenName: volunteerFirstName}) as seen in the code for which I followed G-suite's admin-sdk, but I am not able retrieve the email id, am I doing anything wrong here? Also, I am newbie to google-apps script, please ignore if its a stupid question.
I was able to retrieve it and a bunch of other details using users-list:
function scanSsheet(){
var originalSpreadsheet = SpreadsheetApp.openById('xxxxxxxx-xxxxx-xxxxxxx-xxxx').getSheetByName("Form Responses 1");
var getRange = originalSpreadsheet.getDataRange();
var data = originalSpreadsheet.getDataRange().getValues();
for (var i = 1; i < data.length; i++) {
var volunteerFirstName = data[i][3];
var volunteerLastName = data[i][4];
Logger.log('****************Record No: ' + i + '****************');
Logger.log('volunteerFirstName: ' + data[i][3]);
Logger.log('volunteerLastName: ' + data[i][4]);
Logger.log('fetchUser is called');
fetchUser(volunteerFirstName);
}
}
function fetchUser(volunteerFirstName){
var pageToken;
var membersList = AdminDirectory.Users.list({
domain: 'mydomain.com',
orderBy: 'email',
query: volunteerFirstName,
maxResults: 100,
pageToken: pageToken
});
Logger.log('membersList:' +membersList);
}
Thanks.
Related
I've been struggling with understanding where I went wrong with the following script. The purpose of the script is to delete a row whenever the unique ID in 'individual_client_sheet' matches an id from the row in the two sheets: 'clients_database' and 'clients_sheet'. So far, the code is able to delete the corresponding row in each sheet but the error message "TypeError: Cannot read property '2' of undefined" keeps pooping up and I cannot comprehend why. Secondly, the script would not reset the fields in 'individual_client_sheet' so it seems like it stops working after deleting the records. Here is the script:
function deleteClientRecord () {
// Get Active Sheets
var ss = SpreadsheetApp.getActiveSpreadsheet();
var shClient = ss.getSheetByName ('individual_client_sheet');
var shData = ss.getSheetByName ('clients_database');
var shClientsList = ss.getSheetByName ('clients_sheet');
// Obtain and verify user response
var ui = SpreadsheetApp.getUi();
var response = ui.alert ('Delete', 'Are you sure you want to remove this record?', ui.ButtonSet.YES_NO);
if (response == ui.Button.NO) {
return;
}
var searchValue = shClient.getRange('AF2').getValue();
var shDataValues = shData.getDataRange().getValues();
var shClientsListValues = shClientsList.getDataRange().getValues();
// Delete record from 'clients_database'
var shDataValuesFound = false;
for (var i = 0; i < shDataValues.length; i++) {
var rowValue = shDataValues[i];
if (rowValue[3] == searchValue) {
var iRow = i+1;
shData.deleteRow(iRow);
}
}
// Delete record from All CLients Sheet
var shClientsListValuesFound = false;
for (var j = 0; i < shClientsListValues.length; j++) {
var rowValue2 = shClientsListValues[j];
if (rowValue2[2] == searchValue) {
var jRow = j+1;
shClientsList.deleteRow(jRow);
ui.alert('Record deleted for - Client #' + shClient.getRange('AF2').getValue() + '');
}
}
// Delete Fields
// Checkboxes
shClient.getRange('Z10:AA13').setValue(false);
shClient.getRange('AP5:AQ5').setValue(false);
// Basic Client Info
shClient.getRange('B5:G5').clearContent(); // Business Name
shClient.getRange('AF2').clearContent(); // Client ID
shClient.getRange('B10').clearContent(); // website
shClient.getRange('B12:B13').clearContent(); // billing add
shClient.getRange('B15:B16').clearContent(); // postal add
shClient.getRange('B18').clearContent(); // primary contact
shClient.getRange('B20').clearContent(); // phone
shClient.getRange('B22').clearContent(); // email
shClient.getRange('B26').clearContent(); // additional info 1
shClient.getRange('B28').clearContent(); // additional info 2
// Client Status
shClient.getRange('AN5:AO5').clearContent(); // client status
shClient.getRange('AP5:AQ5').clearContent().setValue(false); // importance
shClientsListValuesFound = true;
shDataValuesFound = true;
return;
}
I assume it is the error line:
for (var j = 0; i < shClientsListValues.length; j++) {
should be j instead of i:
for (var j = 0; j < shClientsListValues.length; j++) {
I'm using the google script to manage the google admin. Below is the script to list all google users in the domain.
If I create conditional formatting directly on the sheet, the rules are deleted whenever the script is launched. That's why I'd like to include the conditional formatting within the script itself, but it's not working?.
Basically what I want are :
if the value of the columns 'is Super Admin?' or 'is Delegated Admin?' are TRUE, then I'd like the rows to be colored in bold red.
And I'm trying to find out how to convert the results of lastLoginTime and creationTime (which are in string ISO8601 to datevalue, I know how to do it using formula, but I don't know how to using the script)
I'd really appreciate it if anyone can guide me.
Many many thanks in advance.
function listAllUser() {
var sheet11 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("SheetNAME");
var sheet11range = sheet11.getRange("I3:Q")
sheet11range.clear()
var data = [];// array to store values
data.push(['Last Name','First Name','Email','orgUnitPath', 'is Suspended?','is Super Admin?','is Delegated Admin?', 'LastLoginTime','Creation']);// store headers
var pageToken, page;
do {
page = AdminDirectory.Users.list({
domain: 'DomainNAME',
pageToken: pageToken,
});
var users = page.users;
if (users) {
for (var i = 0; i < users.length; i++) {
try{
var user = users[i];
data.push([user.name.familyName,user.name.givenName,user.primaryEmail,user.orgUnitPath, user.suspended,user.isAdmin,user.isDelegatedAdmin, user.lastLoginTime , user.creationTime ]);//store in an array of arrays (one for each row)}
}catch (e){}
}}
pageToken = page.nextPageToken;
} while (pageToken);
sheet11.getRange(2,9,data.length,data[0].length).setValues(data).setVerticalAlignment("middle").setWrap(true);
var t1 = sheet11.getRange("I1:P1").merge();
var t1bis = t1.setValue("List of all USERS");
var dated = sheet11.getRange("Q1")
dated.setValue("Last updated: " + Utilities.formatDate(new Date(),Session.getScriptTimeZone(),'dd-MM-yy hh:mm'));
var range = sheet11.getRange("I1:Q2");
range.setFontWeight("Bold").setFontColor("Blue").setHorizontalAlignment("center").setVerticalAlignment("middle").setBackground("#beedda").setWrap(true);
var isSuperAdm = sheet11.getRange("N3:N").getValue();
var isDelegatAdm = sheet11.getRange("O3:O").getValue();
if(isSuperAdm==true || isDelegatAdm==true){
range.setFontWeight('bold').setFontColor('red')
}
}
After looking around for some tutorials, I finally succeeded to have what I wanted, formating the cell :
when the lastLoginTime was before the specific date
when the value of 'is Super Admin?' and 'is Delegated Admin?' are true
function cellsFormatting(){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("SheetName");
var range1 = sheet.getRange("A1:Q2");
range1.setFontWeight("Bold").setFontColor("Blue").setHorizontalAlignment("center").setVerticalAlignment("middle").setBackground("#beedda").setWrap(true);
var range2 = sheet.getRange ("A3:Q");
range2.setVerticalAlignment('middle').setWrap(true);
}
function setRangeToRedBoldFont(cellRange){
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange(cellRange);
var rule = SpreadsheetApp.newConditionalFormatRule()
.whenTextEqualTo("TRUE")
.setFontColor("#FF0000")
.setBold(true)
.setRanges([range])
.build();
var rules = sheet.getConditionalFormatRules();
rules.push(rule);
sheet.setConditionalFormatRules(rules);
}
function setRangeToGrayItalicFont(cellRange){
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange(cellRange);
var rule = SpreadsheetApp.newConditionalFormatRule()
.whenFormulaSatisfied("=DATEVALUE(MID($P3;1;10)) + TIMEVALUE(MID($P3;12;8))<date(2018;8;31)")
.setFontColor("#A9A9A9")
.setItalic(true)
.setRanges([range])
.build();
var rules = sheet.getConditionalFormatRules();
rules.push(rule);
sheet.setConditionalFormatRules(rules);
}
function listAllUser() {
var sheet11 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("SheetName");
var sheet11range = sheet11.getRange("I3:Q")
sheet11range.clear();
cellsFormatting();
var t1 = sheet11.getRange("I1:P1").merge();
var t1bis = t1.setValue("List of all USERS");
var dated = sheet11.getRange("Q1")
dated.setValue("Last updated: " + Utilities.formatDate(new Date(),Session.getScriptTimeZone(),'dd-MM-yy hh:mm')); //will input the date & time when the script was launched
var data = [];// array to store values
data.push(['Last Name','First Name','Email','orgUnitPath', 'is Suspended?','is Super Admin?','is Delegated Admin?', 'LastLoginTime','Creation']);// store headers
var pageToken, page;
do {
page = AdminDirectory.Users.list({
domain: 'DomainNAME',
pageToken: pageToken,
});
var users = page.users;
if (users) {
for (var i = 0; i < users.length; i++) {
try{
var user = users[i];
data.push([user.name.familyName,user.name.givenName,user.primaryEmail,user.orgUnitPath, user.suspended,user.isAdmin,user.isDelegatedAdmin, user.lastLoginTime , user.creationTime ]);//store in an array of arrays (one for each row)}
}catch (e){}
}}
pageToken = page.nextPageToken;
} while (pageToken);
sheet11.getRange(2,9,data.length,data[0].length).setValues(data);
var formatRange = "I3:Q";
setRangeToRedBoldFont(formatRange);
setRangeToGrayItalicFont (formatRange);
}
For the row color:
For user.isAdmin & user.isDelegatedAdmin
function colorLine() {
const ss=SpreadsheetApp.getActive();
const sh=ss.getSheetByName('SheetName');
const rg=sh.getRange(3,9,sh.getLastRow(),9);
const vs=rg.getValues();
vs.forEach((r,i)=>{
if(r[5]||r[6]) {
sh.getRange(i+3,1,1,sh.getLastColumn()).setFontWeight('bold').setFontColor('red');
}
});
}
I have a project to send mail to multiple users, I have written script to send multiple users an Email using App script, but to make the mail more personalized, I want to start mail as "Hi Abhishek Mehta"
Using AdminDirectory.Users.get(userKey, {fields:'name'}) I am able to fetch the name of the users, but not sure how to list them in the sheet.
In normal words, I have 50 Email ids and want to fetch full name of the Email id and want to write it in a Google sheet using Google App Script.
Request help from the community.
name of getUser() returns an object, you'll need to access that object to get the first and surname of the user.
The following script will get all the users in your domain (provided you have admin access) sorted by email and list them in a sheet named Users
function listAllUsers() {
var ss = SpreadsheetApp.getActiveSheet();
var pageToken,
page;
var userInfo = []
do {
page = AdminDirectory.Users.list({
domain: '---------',
orderBy: 'email',
maxResults: 500,
pageToken: pageToken
});
var users = page.users;
if (users) {
for (var i = 0; i < users.length; i++) {
var user = users[i];
try {
userInfo.push([user.primaryEmail, user.name.givenName, user.name.familyName]);
} catch (e) {
userInfo.push([user.primaryEmail, "", ""]);
}
}
} else {
Logger.log('No users found.');
}
pageToken = page.nextPageToken;
} while (pageToken);
var sheet = ss.getSheetByName('Users')
sheet.getRange(2, 1, userInfo.length, userInfo[0].length).setValues(userInfo);
}
To get the names of a list of users you can use the following script. It assumes that the usernames (email addresses) are listed in column A starting in row 2 and without breaks.
There are 3 values in the name object
.givenName is the users first name.
.familyName is the users surname
.fullName is the first name and surname separated by a space
function usersNames() {
var ss = SpreadsheetApp.getActiveSheet();
var data = ss.getRange('A2:A').getValues();
var userNames = [];
for (var i = 0; i < data.length; i++) {
if (data[i][0]) {
var names = AdminDirectory.Users.get(data[i][0]).name
userNames.push([names.givenName, names.familyName]);
} else {
break;
}
}
ss.getRange(2, 2, userNames.length, 2).setValues(userNames)
}
Here is the script for the same.
File id = Example in Bold Letters (https://docs.google.com/spreadsheets/d/1JeNKU366pzsdH-Pg9EsjKENLO0orqunduoOGJJMnKjM4/edit#gid=63023734)
File Name = Name of the sheet under the main spreadsheet, like sheet1 or sheet2
`function getUserName() {
var ss = SpreadsheetApp.openById("File ID");
var sheet = ss.getSheetByName("File Name")
var values = sheet.getDataRange().getValues()
var fileArray = [["User Name"]]
for(i=1; i <values.length; i++)
{
var userKey = values[i][2] // '2' = Cloumn C
try{
var status = "No Name Found"
var status = AdminDirectory.Users.get(userKey, {fields:'name'})
var fullname = status.name.fullName
Logger.log(fullname)
if (status != "No Name Found"){
status = fullname
}
}
catch (e) {
Logger.log(e.message)
var status = e.message
}
fileArray.push([status])
}
var range = sheet.getRange(1, 4, fileArray.length, 1).setValues(fileArray)
}`
I want to create multiple Shared Drives using cell values as Drive Names.
I can fetch the range's values but I dont know how to capture each values inside the array of arrays. I need to get those cell values to set the Drive Names.
Here is my code:
function createDriveID(){
var department = SpreadsheetApp.getActiveSheet().getRange(1,1,SpreadsheetApp.getActiveSheet().getRange("A1").getDataRegion().getLastRow(),1).getValues();
var lastname = SpreadsheetApp.getActiveSheet().getRange(2,2,SpreadsheetApp.getActiveSheet().getRange("B2").getDataRegion().getLastRow(),1).getValues();
var firstname = SpreadsheetApp.getActiveSheet().getRange(3,3,SpreadsheetApp.getActiveSheet().getRange("C3").getDataRegion().getLastRow(),1).getValues();
for (var i=0; i<department.length; i++ ) {
var dep = department[i].toString();
var dept = dep.substring(0,3).toUpperCase();
//Logger.log(dept);
}
for (var x=0; x<lastname.length; x++) {
//var stri = lastname[x].toString();
var lname = lastname[x].toString();
// Logger.log(lname);
}
for (var y=0; y<firstname.length; y++) {
//var string = firstname[y].toString();
var fname = firstname[y].toString();
// Logger.log(fname);
}
//var dept = SpreadsheetApp.getActiveSheet().getRange(37,1,SpreadsheetApp.getActiveSheet().getRange("A37").getDataRegion().getLastRow(),1).setValues(department);
//Generate Drive ID
var newDrive = Drive.newTeamDrive();
var capabilities = Drive.newTeamDriveCapabilities();
capabilities.canAddChildren = true;
capabilities.canDownload = true;
capabilities.canEdit = true;
capabilities.canDeleteDrive = true;
capabilities.canManageMembers = true;
capabilities.canShare = true;
newDrive.capabilities = capabilities;
newDrive.name = 'CCW' + dept + '-' + fname + " " + lname;
var createdDrive = Drive.Drives.insert(newDrive, 'BCK' + Math.random());
//Add Managers on Drive
var permission = Drive.newPermission();
permission.type = 'group'; //Type can be user, domain, group etc.. check role and type section at https://developers.google.com/drive/api/v2/reference/permissions/insert
permission.role = 'fileOrganizer';
permission.value = "xxxx#email.com"; //It can be email or domain or group name based on type
Drive.Permissions.insert(permission, createdDrive.id, {
sendNotificationEmails:false, //Make it true to send notification
supportsTeamDrives:true,
useDomainAdminAccess:false
});
//---------------------Copying of Folders--------------------------------------
var sourcefolder = DriveApp.getFolderById('1O1JSpx0-luxVW31b9Kmz4AYHwJe1dC77');
var destfolder = DriveApp.getFolderById(createdDrive.id);
copyCustomFiles(sourcefolder, destfolder);
//---------------------Copying END----------------------------------
//Add User to Drive
var resource = {
'value': 'xxxx#email.com',
'type': 'group',
'role': 'organizer'
}
Drive.Permissions.insert(resource, createdDrive.id, {"supportsTeamDrives": true});
//End of Generate Drive ID
Logger.log(createdDrive.id);
SpreadsheetApp.getActiveSheet().getRange(37,1,SpreadsheetApp.getActiveSheet().getRange("A37").getDataRegion().getLastRow(),1).setValues(createdDrive.id);
}
Also, I want to get all the Drive IDs inserted on the active sheet.
Expected output will be:
Where MUR is the department, then Last Name and First Name. Those details must be from the cell values.
Any help will be appreciated.
I suggest you to modify your code by adding a for loop within which your nest the rest of your code and iterate through the array elements of your value arrays.
Sample:
function createDriveID(){
var sheet=SpreadsheetApp.getActiveSheet();
var department = sheet.getRange(1,1,SpreadsheetApp.getActiveSheet().getRange("A1").getNextDataCell(SpreadsheetApp.Direction.DOWN).getRow(),1).getValues();
var lastname = sheet.getRange(1,2,SpreadsheetApp.getActiveSheet().getRange("B1").getNextDataCell(SpreadsheetApp.Direction.DOWN).getRow(),1).getValues();
var firstname = sheet.getRange(1,3,SpreadsheetApp.getActiveSheet().getRange("C1").getNextDataCell(SpreadsheetApp.Direction.DOWN).getRow(),1).getValues();
for (var i=0; i<department.length; i++ ) {
var dep = department[i][0].toString();
var dept = dep.substring(0,3).toUpperCase();
var lname = lastname[i][0].toString();
var fname = firstname[i][0].toString();
var newDrive = Drive.newTeamDrive();
var capabilities = Drive.newTeamDriveCapabilities();
capabilities.canAddChildren = true;
capabilities.canDownload = true;
capabilities.canEdit = true;
capabilities.canDeleteDrive = true;
capabilities.canManageMembers = true;
capabilities.canShare = true;
newDrive.capabilities = capabilities;
newDrive.name = 'CCW' + dept + '-' + fname + " " + lname;
var createdDrive = Drive.Drives.insert(newDrive, 'BCK' + Math.random());
...
sheet.getRange(sheet.getLastRow()+1,1).setValue(createdDrive.id);
}
}
Be aware that cell contents retrieved with .getValues() are stored in a 2-D array. Thus, to work with those values you need to specify
both dimesions, e.g. var dep = department[i][0].
Assuming that the number of entries for department, lastname and firstname is equal and corresponds to the number of drives to create -
a single for loop is enough to iterate through all arrays
simultaneously.
Please see my comment to your question considering the correlation between >names and departments.
Here are my 2 spreadsheets:
Gsheet1: Googlesheet for replication (only employee # and employee name would change)
Gsheet2: Config sheet (contains the employee #, employee name, replication status, pubHTML link) that would feed employee # and employee name on Gsheet1
So I have this code that have these functionalities below:
Replicate Gsheet1 depending on the number of employees (I currently have 800+ employees) on Gsheet2 and dump it to a google drive folder.
after replication, will set a "completed" replication status to Gsheet2.
Change the revision properties of the replicated sheet and make it published to web.
Get the link of the published web (pubhtml) and put it on Gsheet2 pubHTML link column.
What happens is when I try to logger.log the results of this code below assuming that I have 2 records on my Gsheet2, it loops three times, the first and third record in loop are the same.
var TemplatesFromDrive = DriveApp.getFolderById(SpreadsheetApp.getActive().getSheetByName("Master Config").getRange("B2").getValue()).getFiles();
while (TemplatesFromDrive.hasNext()) {
var File = TemplatesFromDrive.next();
Logger.log(File.getName());
I was thinking if it's because of the Spreadsheet.flush() that I'm missing. Where is the best place where I can put it on my code so my loop will work properly? Below is my full code.
function replicateCards() {
var ss = SpreadsheetApp.openById('Gsheet2-xxxx');
var copyCard = SpreadsheetApp.openById('Gsheet1-xxxx');
var getID = DriveApp.getFileById(copyCard.getId())
var card = copyCard.getSheetByName("Card");
var mastersheet = ss.getSheetByName("Mastersheet");
var employeeNumber2 = ss.getRange("A2:A").getValues;
var getLastRow = mastersheet.getLastRow();
var destinationFolder = DriveApp.getFolderById('googledrivefolder-xxx');
var changeColorToGrayList = card.getRangeList(['C7', 'E7', 'G7', 'I7', 'K7', 'M7', 'O7', 'Q7',
'C9', 'E9', 'G9', 'I9', 'K9', 'M9', 'O9', 'Q9',
'C11', 'E11', 'G11', 'I11', 'K11', 'M11', 'O11', 'Q11']);
var setValueToZero = card.getRangeList(['C8', 'E8', 'G8', 'I8', 'K8', 'M8', 'O8', 'Q8',
'C10', 'E10', 'G10', 'I10', 'K10', 'M10', 'O10', 'Q10',
'C12', 'E12', 'G12', 'I12', 'K12', 'M12', 'O12', 'Q12']);
for (i = 1; i < getLastRow; i++) {
var badgeStatus = mastersheet.getRange(i + 1, 5).getValue();
if (badgeStatus == "") {
var employeeNumber = mastersheet.getRange(i + 1, 1).getValue();
var employeeName = mastersheet.getRange(i + 1, 2).getValue();
copyCard.getRange("H3").setValue(employeeNumber);
copyCard.getRange("C3").setValue(employeeName);
SpreadsheetApp.flush();
getID.makeCopy(employeeNumber, destinationFolder);
mastersheet.getRange(1 + i, 5).setValue("completed");
SpreadsheetApp.flush();
var files = DriveApp.getFolderById(SpreadsheetApp.openById("Gsheet1-xxxx").getSheetByName("Config Sheet").getRange("B1").getValue()).getFiles();
while (files.hasNext()) {
var file = files.next();
Logger.log(file.getName());
var Found = false;
for (var j = 0; j < employeeNumber2.length; i++) {
if (employeeNumber2[j][0] == file.getName()) {
Found = true;
}
}
if (Found) {
continue;
}
try {
var fileId = file.getId();
var fileName = file.getName();
var revisions = Drive.Revisions.list(fileId);
var lastRevisionId = revisions.items[revisions.items.length - 1].id;
// get the resource and set the publish parameters
var resource = Drive.Revisions.get(fileId, lastRevisionId);
// Logger.log(resource);
resource.published = true;
resource.publishAuto = true;
resource.publishedOutsideDomain = true;
// publish to the web
Drive.Revisions.update(resource, fileId, lastRevisionId);
SpreadsheetApp.flush();
var openByID = SpreadsheetApp.openById(fileId);
SpreadsheetApp.flush();
var googleDriveSheet = openByID.getUrl().replace("edit", "pubhtml"); // or replace("edit", "pub");
SpreadsheetApp.flush();
mastersheet.getRange(1 + j, 9).setValue(googleDriveSheet);
SpreadsheetApp.flush();
} catch (err) {
Logger.log(err);
}
}
}
}
}
Change var getLastRow = mastersheet.getLastRow(); to var getLastRow = mastersheet.getLastRow()-1;
The reason why is because you've started to get your data from the
second row.
If you would start at the third, you should do var getLastRow = mastersheet.getLastRow()-2; ...