The following Google Apps Script tool allows you to quickly append new permissions to existing files within Google/Shared drive. This is quite a niche tool so it is anticipated you would already have a Google Sheet of file IDs/URLs, though there is the option to select an existing Drive folder of files and automatically bring them into this tool.
By inserting email addresses using a comma-and-space format you can optionally select to send a notification email to the new user(s).
You can continue to append further rows to the Google Sheet as existing ones will be skipped once the ‘Status’ column has automatically been marked as ‘Completed’. Alternatively you can clear the Sheet each time for a fresh start.
Quickly append new file permissions via a Google Sheet |
Instructions
- Open the relevant Google Sheet file and then go to “File” and select “Make a copy”, then choose a suitable location. This will make a copy of the tool in your own Google/Shared Drive.
- Start to complete the relevant columns in the Google Sheet. You do not need to add all files at this point but you should ensure you complete the required information for any rows that you do start.
- File ID or URL - required, unless using the 'Select a folder of files' option from the ‘Admin’ menu. Do not convert to a Smart Chip.
- File Name - unless using the ‘Select a folder of files’ option from the ‘Admin’ menu, please use the ‘Get file names’ option to scan through your existing IDs/URLs and automatically populate their name.
- Editor | Commenter | Viewer - optional. It is possible to enter more than one email address here, as long as you separate each one by a comma and a space. For example: john.smith@york.ac.uk, jane.doe@york.ac.uk, joe.bloggs@york.ac.uk
- Send Email Notification - optional - defaults to ‘No’ if left blank. Uses the standard automated Google email for when an item is shared.
- Status - will be updated automatically.
- Notes - optional - just a column for you if you wish to add some information.
- If you wish to append further Columns from ‘I’ onwards then you may.
- Select a folder of files - use this option if you do not have an existing list of file IDs/URLs from another Google Sheet to paste in. This will allow you to collate a Google Drive folder of files (they must be all at one level i.e. the tool will not iterate through sub-folders of files).
- Click the ‘Admin’ option from the menu bar at the top and then ‘Select a folder of files’. Read the information in the dialogue box carefully and click ‘Yes’ to proceed.
- Search for your Google Drive folder by entering its name into the search bar at the top left. Click once to highlight it then click the ‘Select’ button. Be patient at this point as there may be a delay whilst all of your files are collated into the Google Sheet and the pop-up remains on-screen.
- You can now complete the information in the Google Sheet as per Step 2 above, ignoring columns A and B.
- Append file permissions.
- Once you have completed the Google Sheet click the ‘Admin’ option from the menu bar at the top and then ‘Append file permissions’.
- This will now automatically loop through each row and append permissions. The ‘Status’ column will be updated for you. This column also serves as a way of skipping rows should you wish to append further files in future - so unless it is blank the said row will be ignored. Whilst this is running please leave the Google Sheet open, but you can continue to work on other tasks should you wish. The process will not slow down your PC or internet connection.
- A pop-up message will appear in the Google Sheet at the end to inform you when it has completed.
Caveats
- Fixed columns/rows
- You must not add/delete/move any of the blue columns (A to H) otherwise the tool will break. Nor should you try to insert a new row above the current row 3. You absolutely can add further columns/data from I onwards if you wish.
- Smart Chips
- Do not accept the automated Google prompt to convert your File URLs (Column A) into a Smart Chip (this is usually by clicking on the prompt or by pressing the Tab key). Whilst this is useful and looks nicer in other circumstances, it will break the automation here unfortunately as Google have not made Apps Script compatible with them.
Download
Append Drive file permissions Tool download (please use 'File' > 'Make a copy' for your own version).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* A number of global variables that are re-used throughout this script. | |
*/ | |
// 5 minute maximum runtime | |
var maxRuntime = 5 * 60 * 1000; | |
var ss = SpreadsheetApp.getActiveSpreadsheet(); | |
var timeZone = ss.getSpreadsheetTimeZone(); | |
var logSheet = ss.getSheetByName('Log'); | |
var statusColumnNo = 7; | |
/** | |
* @OnlyCurrentDoc | |
* | |
* Creates Menu item. | |
* | |
*/ | |
function onOpen() { | |
SpreadsheetApp.getUi() | |
.createMenu('Admin') | |
.addItem('Select a folder of files', 'pickerPopup') | |
.addItem('Get file names', 'getFileNames') | |
.addItem('Append file permissions', 'setPermissions') | |
.addToUi(); | |
}; | |
function setPermissions() { | |
main(); | |
}; | |
function getFolderID(id) { | |
pickerFolderID(id); | |
}; | |
function getFileNames() { | |
fileNames(); | |
}; | |
/** | |
* Performs all of the functions for the Append Drive file permissions system. | |
*/ | |
function main() { | |
try { | |
logEvent("Starting 'main' Function."); | |
// get start time so can manage duration of script and avoid timeout | |
var startTime = new Date().getTime(); | |
// create variable for capturing results | |
var errorFlag = false; | |
var metricsSent = false; | |
// create regular expression for testing valid email address | |
var emailAddressRegEx = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/gm; | |
// get Files Sheet | |
var filesSheet = ss.getSheetByName('Files'); | |
logEvent("Successfully got the 'Files' Sheet."); | |
// get Column and call Function to retrieve last row number, then subtract 2 for Headings | |
var columnToCheck = filesSheet.getRange("A:A").getValues(); | |
var lastRowNo = getLastRowSpecial(columnToCheck) - 2; | |
// check no error with previous Function | |
if (lastRowNo !== false) { | |
// proceed as no error | |
// get the data in the Files sheet | |
var lastCol = filesSheet.getLastColumn() - 1; | |
var data = filesSheet.getRange(3, 1, lastRowNo, lastCol).getValues(); | |
var dataLength = data.length; | |
// create counter for number of rows actioned | |
var rowsActionedCounter = 0; | |
// loop through spreadsheet data ******************************** | |
for (var i = 0; i < dataLength; i++) { | |
// create flag to determine if a file has been updated | |
var aFileHasBeenUpdated = false; | |
// log row number | |
var rowNo = i + 3; | |
logEvent("Current row number is: " + rowNo); | |
// get value of 'File ID or URL' and 'Status' columns to see if skipping row | |
var fileIDUrl = data[i][0]; | |
var status = data[i][6]; | |
logEvent("fileIDUrl column is: " + fileIDUrl); | |
logEvent("status column is: " + status); | |
if ((fileIDUrl != "") && (status == "")) { | |
// proceed with current row | |
// check file reachable for user running script ************************ | |
try { | |
// get the file | |
var fileID = fileIDUrl.match(/[-\w]{25,}/); | |
var file = DriveApp.getFileById(fileID); | |
var fileName = file.getName(); | |
logEvent("Successfully got file: " + fileName); | |
} catch (error) { | |
logEvent("Unable to get Drive file: " + error.stack); | |
// run Function to launch HTML popup | |
var popupTitle = "Google Drive file error"; | |
var popupMessage = "Please check you have provided the correct file ID/URL.<br/><br/>Message: " + error.stack; | |
htmlPopup(popupTitle, popupMessage); | |
errorFlag = true; | |
// break out of loop | |
break; | |
}; | |
// check file reachable for user running script ************************ | |
// extract row data | |
var editorEmails = data[i][2]; | |
var commenterEmails = data[i][3]; | |
var viewerEmails = data[i][4]; | |
var sendNotificationEmail = data[i][5]; | |
// check if notification emails need sending | |
if (sendNotificationEmail == "Yes") { | |
logEvent("Option to send notification emails is Yes."); | |
var optionalArgs = { | |
sendNotificationEmails: true, | |
supportsAllDrives: true | |
}; | |
} else { | |
logEvent("Option to send notification emails is No."); | |
var optionalArgs = { | |
sendNotificationEmails: false, | |
supportsAllDrives: true | |
}; | |
}; | |
// add Editors ***************************************** | |
if (editorEmails.length != 0) { | |
var editorEmailAddresses = editorEmails.split(", "); | |
var editorEmailAddressesLength = editorEmailAddresses.length; | |
for (var j = 0; j < editorEmailAddressesLength; j++) { | |
// extract individual email address | |
var singleEmailAddress = editorEmailAddresses[j]; | |
// test valid email address against RegEx | |
var checkEmailAddress = singleEmailAddress.match(emailAddressRegEx); | |
if (checkEmailAddress) { | |
// valid email address, proceed | |
var resource = { | |
value: singleEmailAddress, | |
type: 'user', | |
role: 'writer' | |
}; | |
Drive.Permissions.insert(resource, fileID, optionalArgs); | |
} else { | |
// invalid email addresss | |
logEvent("Invalid email address: " + singleEmailAddress); | |
// run Function to launch HTML popup | |
var popupTitle = "Invalid email address"; | |
var popupMessage = "There is a problem with the following email address, please ensure you have entered it correctly into the Google Sheet with a comma and space.<br/><br/>Email address: " + singleEmailAddress; | |
htmlPopup(popupTitle, popupMessage); | |
errorFlag = true; | |
// break out of loop | |
break; | |
}; | |
}; | |
logEvent("Completed Editor email addresses."); | |
// update flag so know that a file has been updated | |
aFileHasBeenUpdated = true; | |
} else { | |
logEvent("No Editor email addresses to add."); | |
}; | |
// add Editors ***************************************** | |
// add Commenters ***************************************** | |
if (errorFlag === false) { | |
if (commenterEmails.length != 0) { | |
var commenterEmailAddresses = commenterEmails.split(", "); | |
var commenterEmailAddressesLength = commenterEmailAddresses.length; | |
for (var j = 0; j < commenterEmailAddressesLength; j++) { | |
// extract individual email address | |
var singleEmailAddress = commenterEmailAddresses[j]; | |
// test valid email address against RegEx | |
var checkEmailAddress = singleEmailAddress.match(emailAddressRegEx); | |
if (checkEmailAddress) { | |
// valid email address, proceed | |
var resource = { | |
value: singleEmailAddress, | |
type: 'user', | |
role: 'reader', | |
additionalRoles: ["commenter"] | |
}; | |
Drive.Permissions.insert(resource, fileID, optionalArgs); | |
} else { | |
// invalid email addresss | |
logEvent("Invalid email address: " + singleEmailAddress); | |
// run Function to launch HTML popup | |
var popupTitle = "Invalid email address"; | |
var popupMessage = "There is a problem with the following email address, please ensure you have entered it correctly into the Google Sheet with a comma and space.<br/><br/>Email address: " + singleEmailAddress; | |
htmlPopup(popupTitle, popupMessage); | |
errorFlag = true; | |
// break out of loop | |
break; | |
}; | |
}; | |
logEvent("Completed Commenter email addresses."); | |
// update flag so know that a file has been updated | |
aFileHasBeenUpdated = true; | |
} else { | |
logEvent("No Commenter email addresses to add."); | |
}; | |
} else { | |
// do nothing as errors have occurred | |
}; | |
// add Commenters ***************************************** | |
// add Viewers ***************************************** | |
if (errorFlag === false) { | |
if (viewerEmails.length != 0) { | |
var viewerEmailAddresses = viewerEmails.split(", "); | |
var viewerEmailAddressesLength = viewerEmailAddresses.length; | |
for (var j = 0; j < viewerEmailAddressesLength; j++) { | |
// extract individual email address | |
var singleEmailAddress = viewerEmailAddresses[j]; | |
// test valid email address against RegEx | |
var checkEmailAddress = singleEmailAddress.match(emailAddressRegEx); | |
if (checkEmailAddress) { | |
// valid email address, proceed | |
var resource = { | |
value: singleEmailAddress, | |
type: 'user', | |
role: 'reader' | |
}; | |
Drive.Permissions.insert(resource, fileID, optionalArgs); | |
} else { | |
// invalid email addresss | |
logEvent("Invalid email address: " + singleEmailAddress); | |
// run Function to launch HTML popup | |
var popupTitle = "Invalid email address"; | |
var popupMessage = "There is a problem with the following email address, please ensure you have entered it correctly into the Google Sheet with a comma and space.<br/><br/>Email address: " + singleEmailAddress; | |
htmlPopup(popupTitle, popupMessage); | |
errorFlag = true; | |
// break out of loop | |
break; | |
}; | |
}; | |
logEvent("Completed Viewer email addresses."); | |
// update flag so know that a file has been updated | |
aFileHasBeenUpdated = true; | |
} else { | |
logEvent("No Viewer email addresses to add."); | |
}; | |
} else { | |
// do nothing as errors have occurred | |
}; | |
// add Viewers ***************************************** | |
if (aFileHasBeenUpdated === true) { | |
// update Status Column | |
filesSheet.getRange(rowNo, statusColumnNo).setValue("Completed"); | |
// increment rows actioned counter by 1 | |
rowsActionedCounter++; | |
} else { | |
// no file has been updated | |
}; | |
} else { | |
logEvent("Skipping row."); | |
}; | |
// perform runtime check ************************************************ | |
// get current time | |
var endTime = new Date().getTime(); | |
// find elapsed time by subtracting from start time | |
var elapsedTime = endTime - startTime; | |
// check against maximum runtime | |
var timeLimitExceeded = elapsedTime >= maxRuntime; | |
// check status | |
if (timeLimitExceeded) { | |
// runtime has been met/exceeded | |
logEvent('Runtime has been met/exceeded.'); | |
// run Function to launch HTML popup | |
var popupTitle = "Time limit reached"; | |
var popupMessage = "The maximum Google runtime has been reached but there are still files to action. To continue please close this dialogue box and select to run the tool again from the Menu."; | |
htmlPopup(popupTitle, popupMessage); | |
errorFlag = true; | |
// break out of loop to prevent script from continuing | |
break; | |
} else { | |
// runtime has not been met/exceeded, script can continue looping through rows | |
}; | |
// perform runtime check ************************************************ | |
}; | |
// loop through spreadsheet data ******************************** | |
} else { | |
// error occured, do nothing as popup already displayed | |
errorFlag = true; | |
}; | |
// determine final popup message | |
if (errorFlag === false) { | |
// no errors have occured | |
// run Function to launch HTML popup | |
var popupTitle = "Successfully completed"; | |
var popupMessage = rowsActionedCounter + " files have been appended with permissions."; | |
htmlPopup(popupTitle, popupMessage); | |
} else { | |
// errors have occured, do nothing as popup box already being displayed | |
}; | |
logEvent("Completed 'main' Function."); | |
} catch (error) { | |
logEvent("Error with 'main' Function: " + error.stack); | |
// run Function to launch HTML popup | |
var popupTitle = "Error with 'main' Function"; | |
var popupMessage = "Message: " + error.stack; | |
htmlPopup(popupTitle, popupMessage); | |
}; | |
}; | |
/** | |
* Function to get last row number from specified column. | |
* Used as future additions to the Google Sheet may include tickboxes which affect 'getRange()'. | |
*/ | |
function getLastRowSpecial(columnToCheck) { | |
try { | |
logEvent("Started 'getLastRowSpecial' Function."); | |
// reset variables before using in loop below | |
var rowNum = 0; | |
var blank = false; | |
// loop through the array and check the value in the cell **************************** | |
for (var row = 0; row < columnToCheck.length; row++) { | |
// check if cell value is empty AND 'blank' variable is not false | |
var rowValue = columnToCheck[row][0]; | |
if ((rowValue == "") && (!blank)) { | |
// if true then set row number variable to value of loop and flag it's true | |
rowNum = row; | |
blank = true; | |
} | |
else if (rowValue != "") { | |
// if the cell value is not empty (contains data) then flag it's not blank | |
blank = false; | |
} | |
} | |
// loop through the array and check the value in the cell **************************** | |
logEvent("Last Row is: " + rowNum); | |
logEvent("Completed 'getLastRowSpecial' Function."); | |
return rowNum; | |
} catch (error) { | |
logEvent("Error with 'getLastRowSpecial' Function: " + error.stack); | |
// run Function to launch HTML popup | |
var popupTitle = "Error with 'getLastRowSpecial' Function"; | |
var popupMessage = "Message: " + error.stack; | |
htmlPopup(popupTitle, popupMessage); | |
// return error flag | |
return false; | |
}; | |
}; | |
/** | |
* Display a dialog box to prompt user if they wish to open Google Picker. | |
*/ | |
function pickerPopup() { | |
var ui = SpreadsheetApp.getUi(); | |
var result = ui.alert( | |
'Open Folder Picker', | |
'Select this option if you have a single Google Drive folder full of files (no sub-folders). Only click once to select your folder (do not double-click it). It make take up to 10 seconds to load.', | |
ui.ButtonSet.YES_NO | |
); | |
// Process the user's response. | |
if (result == ui.Button.YES) { | |
// User clicked "Yes". | |
showPicker(); | |
} else { | |
// User clicked "No" or X in the title bar. | |
}; | |
}; | |
function showPicker() { | |
var html = HtmlService.createHtmlOutputFromFile('Picker.html') | |
.setWidth(650) | |
.setHeight(500) | |
.setSandboxMode(HtmlService.SandboxMode.IFRAME); | |
SpreadsheetApp.getUi().showModalDialog(html, 'Select Folder'); | |
}; | |
function getOAuthToken() { | |
DriveApp.getRootFolder(); | |
return ScriptApp.getOAuthToken(); | |
}; | |
<!DOCTYPE html> | |
<html> | |
<head> | |
<!-- Add the standard Google Style Sheet. --> | |
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css"> | |
<script type="text/javascript"> | |
var DIALOG_DIMENSIONS = { | |
width: 650, | |
height: 500 | |
}; | |
var pickerApiLoaded = false; | |
function onApiLoad() { | |
gapi.load('picker', { | |
'callback': function() { | |
pickerApiLoaded = true; | |
} | |
}); | |
google.script.run.withSuccessHandler(createPicker).withFailureHandler(showError).getOAuthToken(); | |
} | |
function createPicker(token) { | |
if (pickerApiLoaded && token) { | |
var docsView = new google.picker.DocsView() | |
.setParent('root') | |
.setIncludeFolders(true) | |
.setMode(google.picker.DocsViewMode.LIST) | |
.setMimeTypes('application/vnd.google-apps.folder') | |
.setSelectFolderEnabled(true); | |
var picker = new google.picker.PickerBuilder() | |
.addView(docsView) | |
.hideTitleBar() | |
.setSize(DIALOG_DIMENSIONS.width - 2, DIALOG_DIMENSIONS.height - 2) | |
.setOAuthToken(token) | |
.setCallback(pickerCallback) | |
.setOrigin("https://docs.google.com") | |
.build(); | |
picker.setVisible(true); | |
} else { | |
showError('Unable to load the file picker.'); | |
}; | |
}; | |
/* | |
Function used as SuccessHandler for 'pickerCallback' so will only close dialogue | |
box if that codes runs correctly. | |
*/ | |
function folderInserted(){ | |
google.script.host.close(); | |
} | |
/** | |
* A callback function that extracts the chosen document's metadata from the | |
* response object. For details on the response object, see | |
* https://developers.google.com/picker/docs/result | |
* | |
* @param {object} data The response object. | |
*/ | |
function pickerCallback(data) { | |
var action = data[google.picker.Response.ACTION]; | |
if (action == google.picker.Action.PICKED) { | |
var doc = data[google.picker.Response.DOCUMENTS][0]; | |
var id = doc[google.picker.Document.ID]; | |
/* | |
Runs Apps Script Function 'insertFolderURL' and passes in item Id from Google Picker. | |
A failure to run will trigger below 'showError' Function. | |
A success run will trigger above 'folderInserted' Function and close dialogue box. | |
*/ | |
google.script.run.withSuccessHandler(folderInserted).withFailureHandler(showError).getFolderID(id); | |
} | |
else if (action == google.picker.Action.CANCEL) { | |
google.script.host.close(); | |
} | |
} | |
function showError(message) { | |
document.getElementById('result').innerHTML = 'Error: ' + message; | |
} | |
</script> | |
</head> | |
<body> | |
<div> | |
<p id='result'></p> | |
</div> | |
<script type="text/javascript" src="https://apis.google.com/js/api.js?onload=onApiLoad"></script> | |
</body> | |
</html> | |
/** | |
* Take Google Drive Folder ID passed from Google Picker. | |
*/ | |
function pickerFolderID(id) { | |
try { | |
logEvent("Starting 'pickerFolderID' Function."); | |
logEvent("Google Drive folder ID from Picker is: " + id); | |
// create emtpy array for pushing folder/file data into to append to Sheet at very end | |
var fileDetailsArray = []; | |
// create variable to use as Counter for index of files | |
var fileCounter = 0; | |
// get Google Drive folder of files | |
var sourceFolder = DriveApp.getFolderById(id); | |
// get files inside of folder | |
var files = sourceFolder.getFiles(); | |
while (files.hasNext()) { | |
var childFile = files.next(); | |
// create clickable file name link | |
var fileName = childFile.getName(); | |
var fileUrl = childFile.getUrl(); | |
var hyperlink = '=HYPERLINK("' + fileUrl + '","' + fileName + '")'; | |
// get File ID | |
var fileId = childFile.getId(); | |
// push data into beginning of array for later adding back into Google Sheet | |
fileDetailsArray.unshift([fileId, hyperlink]); | |
// increment file Counter by 1 | |
fileCounter++; | |
}; | |
logEvent("Number of files searched through is: " + fileCounter); | |
// get Files Sheet | |
var filesSheet = ss.getSheetByName('Files'); | |
logEvent("Successfully got the 'Files' Sheet."); | |
// get Column and call Function to retrieve last row number, then subtract 2 for Headings | |
var columnToCheck = filesSheet.getRange("A:A").getValues(); | |
var lastRowNo = getLastRowSpecial(columnToCheck); | |
// check no error with previous Function | |
if (lastRowNo !== false) { | |
// now append row data to Google Sheet in one go | |
var arrayLength = fileDetailsArray.length; | |
var arrayWidth = fileDetailsArray[0].length; | |
filesSheet.getRange(lastRowNo + 1, 1, arrayLength, arrayWidth).setValues(fileDetailsArray); | |
logEvent("Completed 'pickerFolderID' Function."); | |
} else { | |
// error occured, do nothing as popup already displayed | |
}; | |
} catch (error) { | |
logEvent("Error with 'pickerFolderID' Function: " + error.stack); | |
// run Function to launch HTML popup | |
var popupTitle = "Error with 'pickerFolderID' Function"; | |
var popupMessage = "Message: " + error.stack; | |
htmlPopup(popupTitle, popupMessage); | |
}; | |
}; | |
/** | |
* Loop through Google Sheet, collate file names and input back into Sheet. | |
*/ | |
function fileNames() { | |
try { | |
logEvent("Starting 'fileNames' Function."); | |
// create variable for capturing errors | |
var errorFlag = false; | |
// get Files Sheet | |
var filesSheet = ss.getSheetByName('Files'); | |
logEvent("Successfully got the 'Files' Sheet."); | |
// get Column and call Function to retrieve last row number, then subtract 2 for Headings | |
var columnToCheck = filesSheet.getRange("A:A").getValues(); | |
var lastRowNo = getLastRowSpecial(columnToCheck) - 2; | |
// check no error with previous Function | |
if (lastRowNo !== false) { | |
// get the data in the Files sheet | |
var data = filesSheet.getRange(3, 1, lastRowNo, 2).getValues(); | |
var dataLength = data.length; | |
// create variable to use as Counter for index of files | |
var fileCounter = 0; | |
// loop through spreadsheet data ******************************** | |
for (var i = 0; i < dataLength; i++) { | |
// get value of 'File ID or URL' and 'File Name' column to see if skipping row | |
var fileIDUrl = data[i][0]; | |
var existingFileName = data[i][1]; | |
if ((fileIDUrl != "") && (existingFileName == "")) { | |
// proceed with current row | |
var rowNo = i + 3; | |
// check file reachable for user running script ************************ | |
try { | |
// get the file | |
var fileID = fileIDUrl.match(/[-\w]{25,}/); | |
var file = DriveApp.getFileById(fileID); | |
var fileName = file.getName(); | |
var fileUrl = file.getUrl(); | |
var hyperlink = '=HYPERLINK("' + fileUrl + '","' + fileName + '")'; | |
} catch (error) { | |
logEvent("Unable to get Drive file: " + error.stack); | |
// run Function to launch HTML popup | |
var popupTitle = "Google Drive file error"; | |
var popupMessage = "Please check you have provided the correct file ID/URL<br/><br/>. Message: " + error.stack; | |
htmlPopup(popupTitle, popupMessage); | |
errorFlag = true; | |
// break out of loop | |
break; | |
}; | |
// check file reachable for user running script ************************ | |
// append file name to Google Sheet | |
filesSheet.getRange(rowNo, 2).setValue(hyperlink); | |
// increment file Counter by 1 | |
fileCounter++; | |
} else { | |
// skip row as blank | |
}; | |
}; | |
// determine final popup message | |
if (errorFlag === false) { | |
// no errors have occured | |
// run Function to launch HTML popup | |
var popupTitle = "Successfully completed"; | |
var popupMessage = fileCounter + " file names have been collated."; | |
htmlPopup(popupTitle, popupMessage); | |
} else { | |
// errors have occured, do nothing as popup box already being displayed | |
}; | |
logEvent("Completed 'fileNames' Function."); | |
} else { | |
// error occured, do nothing as popup already displayed | |
}; | |
} catch (error) { | |
logEvent("Error with 'fileNames' Function: " + error.stack); | |
// run Function to launch HTML popup | |
var popupTitle = "Error with 'fileNames' Function"; | |
var popupMessage = "Message: " + error.stack; | |
htmlPopup(popupTitle, popupMessage); | |
}; | |
}; | |
/** | |
* Function to output messages to the 'Log' sheet. | |
* Can be called anywhere else in script. | |
*/ | |
function logEvent(action) { | |
// get the user running the script | |
var theUser = Session.getActiveUser().getEmail(); | |
// create and format a timestamp | |
var dateTime = new Date(); | |
var niceDateTime = Utilities.formatDate(dateTime, timeZone, "dd/MM/yyyy HH:mm:ss"); | |
// create array of data for pasting into log sheet | |
var logData = [niceDateTime, theUser, action]; | |
// append details into next row of log sheet | |
logSheet.appendRow(logData); | |
}; | |
/** | |
* Display a modal dialog box with custom HtmlService content. | |
* Does not suspend the script. | |
*/ | |
function htmlPopup(popupTitle, popupMessage) { | |
var htmlOutput = HtmlService | |
.createHtmlOutput(popupMessage) | |
.setWidth(380) | |
.setHeight(180); | |
SpreadsheetApp.getUi().showModalDialog(htmlOutput, popupTitle); | |
}; |
No comments:
Post a Comment