Find and Select or Format rows in Google Sheets with Apps Script

In this tutorial, we create 3 Google Apps Script functions that are used to:

  1. Find and select the row containing the first or last value in a Google Sheets sheet tab.
  2. Find and select all rows containing the search value.
  3. Format all rows containing the search text.

You can grab a copy of the starter Google Sheet to play along here:

Find & Select or Format Rows – Tutorial

This tutorial accompanies the YouTube video of the same name:

https://youtu.be/Y7rnQT6qYiA

All functions are built to be run from another function, making it easy for you to integrate them into your own projects.

For our example, we will use the runies function for this purpose.

All three of the  examples below take two arguments as parameters:

  • text – the search text.
  • sheetName – the Name of the selected sheet tab.

These functions rely on the Apps Script Spreadsheet App Text finder class to search for the target text within the range.

All examples search a selected sheet tab. However, you can easily modify the script to search a specific range or the entire Google Sheets workbook. You can learn more about how to do this here:

Find All Values in Google Sheets with Apps Script

Find and activate the first or last row in a Google Sheet with Apps Script

Lines 10-12 – In this scenario, we activate the first (findNext()) or last (findPrevious())found row based on a search item that can be found anywhere in the row. We then store this cell range in the cell variable.

Line 17 –  From the cell variable, we can select the Spreadsheet App Range getRow() method to get the row number of the cell.

Line 19-21 – Next, we can activate the range of the selected row using the activate method.

We set the entire range by using A1-notation here within a template literal (that is a string within backticks ()). In Google Sheets, we can set the full width of a sheet by leaving the last column value blank in the notation, for example:

A1:1 or even 1:1.

Incidentally, you can also select a portion of the width by including an end letter in the range, for example:

A1:K1 or in the script .getRange(A${row}:K${row}`)

You can learn more about selecting the first or last found values in this tutorial:

Find first, last or nth value in a Google Sheets range with Apps Script

If you have found the tutorial helpful, why not shout me a coffee ☕? I'd really appreciate it.

Find and activate first row based on a search value in Google Sheets
Example finds the first instance of ‘Koala’ in the range and selects the row.

Find and activate all rows in a Google Sheet with Apps Script

In this example, we select all of the rows containing the target search value.

Line 13 – First, we modify the Text Finder variable to the findAll method and rename the variable. This will return an array of all the cells where the values are found as an array.

Lines 15-16 – Now, we can map over each item in the array creating a new array of ranges that contain A1-notation of the selected row.

Line 18 – Finally, we can use the Spreadsheet App Sheet Class getRangeList() method to collect all ranges in our array and then activate them.

Find and activate all rows based on a search value in Google Sheets
Finds and activates all rows in the range that contain ‘Koala’.

Find and format all rows in a Google Sheet with Apps Script

This last function is virtually the same as the previous one. However, we are doing something much more useful, we are programmatically updating the format of the selected rows.

Lines 18-21 – Using the getRangeList method, we can modify the formatting of any range in the list. In our example, we set the background of the row to a dark blue, changed the text colour to white and bolded the font.

Find and format all rows based on a search value in Google Sheets
Finds and formats all rows containing the search item ‘Koala’.

More formatting methods you can use.

Here is a list of common formatting methods that you can apply to a range list:

  1. Clear FormatclearFormat() – Clears the formatting of the selected range.
  2. Set background ColoursetBackgroundColor(colour) – Use CSS notation like hexadecimal colours, colour names or RGB colours
  3. Set font ColoursetFontColor(colour)– Use CSS notation like hexadecimal colours, colour names or RGB colours.
  4. Set font WeightsetFontWeight(type) – Either “bold” or “normal”.
  5. Set font Size= setFontSize(size) – The font size as a number.
  6. Set font StylesetFontStyle(style) – The style, e.g. “Helvetica”, “Poppins”.
  7. Set vertical alignmentsetVerticalAlignment(alignment) – “top”, “middle” or “bottom”.
  8. Set horizontal alignmentsetHorizontalAlignment(alignment) – “left”, “center”, “right”.
  9. Set text rotationsetTextRotation() – Sets the rotation of the text in each cell in degrees from the original horizontal plain.

In the next tutorial, we will cover how to hide and unhide rows based on found values in a range. The process is a little different, so well worth checking out.

Subscribe to get an email when the next tutorial in this series comes out or get regular updates on my latest tutorials.

If you have found the tutorial helpful, why not shout me a coffee ☕? I'd really appreciate it.

~Yagi

Performance of Google Apps Script Text Finder Class on 2 Approaches to Searching Large Datasets

Inspired by research into a recent blog post, the Google Apps Script Text Finder Class’ Find All (findAll()) and Find Next (findNext()) methods were benchmarked over two different datasets containing 50,000 rows. The first dataset contained 1,000 cells matching the search text. The second dataset contained 100 matching cells.

For each dataset, a test was conducted to retrieve either the first 10 matching cells or the first 100 matching cells. The Find All and Find Next approaches were tested and compared on each test.

It was expected that Find Next would perform best on the condition where the dataset contained a large number of found items and only a small number of first cells needed to be reported. The benchmark results suggest that this hypothesis is most likely.

First number of cells to retrieve Test Function Avg. run time over 100 runs. Fastest Function Fastest Avg. Time Avg. time Difference
1000 items to find
10
1
v2 findAll 1626.24 v3 findNext 1368.45 257.79
v3 findNext 1368.45
50
2
v2 findAll 1578.19 v2 findAll 1578.19 4993.61
v3 findNext 6571.8
100 items to find
10
3
v2 findAll 360.94 v2 findAll 360.94 975.16
v3 findNext 1336.1
50
4
v2 findAll 377.13 v2 findAll 377.13 6175.59
v3 findNext 6552.72

Table: The average time in milliseconds of 100 runs of each test of Apps Script Text Finder findAll() and findNext() methods. Image link for mobile-friendly viewers.

Method

Sample Data

Two columns of data 50,000 rows deep were generated for this test. Each cell in each column consisted of a number; either 1, 2, 3, 4 or 5. An equal spread of numbers 1 through 4 where added to each row. Each column differs by the number of 5s in each row:

  • Col A: 1,000 5’s
  • Col B: 100 5’s

Each column was then selected and randomised with: Data > Randomise range.

Test

Two functions are compared to test their performance based on four test conditions based on 100 runs of each test:

  1. Retrieve the first 10 cells containing the search text where the range contains 1,000 matching search items.
  2. Retrieve the first 50 cells containing the search text where the range contains 1,000 matching search items.
  3. Retrieve the first 10 cells containing the search text where the range contains 100 matching search items.
  4. Retrieve the first 50 cells containing the search text where the range contains 100 matching search items.

The time in milliseconds was recorded using the JavaScript Date.now() method before and after the functions were run. The difference in time in milliseconds was then appended to an array and added to a Google Sheet column for each test type. This culminated in 8 sets of 100 results.

The average of each test was then recorded and used to compare performance.

Note: Performance.now() is not available in Google Apps Script. 

Code

All code and results can be found copied from this sheet:

Analysis of Google Apps Script Create Finder Class Retrieve n found values

To explore the code and run your own independent tests, make a copy of the Google Sheet: File > Make a copy.

More detailed breakdowns of the code for each test function can be found in the source tutorial.

Note! There is no v1. The version numbers refer to the tutorial related to this post.

Main Test RUN

This function ran all the test conditions. Modify colPastePosition to add the culminated times to the desired columns. Then uncomment the desired run.

test_v2 – Google Apps Script Text Finder Class- findAll()

Code breakdown can be found here: link.

This function retrieves the full list of all found cells using the findAll() method from the Text Finder Class. All available found items in the range are then stored in the found variable.

It then relies on a for-loop to iterate through each cell and collect the cell location using the Spreadsheet App Class’ range getA1Notation method. Each cell location is then stored in the locations variable as an array item before returning the array to the initialising function.

The for-loop breaks when the total number of required cell items (the position) equal the index variable (i) in the loop.

test_v3 – Google Apps Script Text Finder Class- findNext()

Code breakdown can be found here: link.

In this function, a call is made to the spreadsheet to retrieve the found cell value each time findNext() method of the Text Finder Class is called. On each iteration, the getA1Notation method is used to retrieve the cell location. This location is then stored as an array value in the locations variable before being returned to the initiating function.

The function used a while-loop to iterate through each next item found until the counter – or the number of required cells to collect – is reached.

Results & Discussion

Analysis of Google Apps Script Create Finder Class Retrieve n found values
Performance in Milliseconds to Retrieve the first 10 or 50 Matching Values over a 50,000 Row Range Contain Either 1000 or 100 Matchable items Using the Google Apps Script Spreadsheet App Finder Class.

Test 1: Retrieve the first 10 cells containing the search text where the range contains 1,000 matching search items.

Version 3 –findNext() performed better on average when there were 1000 potential items to find in the range but only the first 10 items need to be selected. Versions 3’s average speed was 1368.45ms compared to version 2’s average run speed of 1826.24ms. This is a performance increase of 257.79ms for version 3.

Version 2’s lower performance is likely due to needing to collect all available found cells before it can extract the top 10 items.

Version 3, makes 10 calls to the Google Sheets in this example. Compared to version 2, this takes relatively less time than collecting all available found cell references to the search item.

TEST 1: 1,000 randomised items to find in 50,000. Return first 10 matches using v2-findAll and v3-findNext functions.
TEST 1: 1,000 randomised items to find in 50,000. Return first 10 matches using v2-findAll and v3-findNext functions.

Test 2: Retrieve the first 50 cells containing the search text where the range contains 1,000 matching search items.

Version 2 – findAll() performed significantly better over 100 runs than version 3 when retrieving the top 50 found cells from a possible 1000. Version 2 was, on average, 4993.61ms faster at an average runtime of 1578.19ms compared to version 3’s sluggish 6571.80ms average.

It was expected that test one and test two’s times for version 2 would be similar and there are only 48.05ms between their average runtimes.

Version 3’s poor performance is likely due to its reliance on calling the spreadsheet to collect the cell data on all 50 calls it needs to make.

TEST 2: 1,000 randomised items to find in 50,000. Return first 50 matches using v2-findAll and v3-findNext functions.
TEST 2: 1,000 randomised items to find in 50,000. Return first 50 matches using v2-findAll and v3-findNext functions.

Test 3: Retrieve the first 10 cells containing the search text where the range contains 100 matching search items.

Version 2, again, performed better by 975.16ms than version 3 when there was a smaller potential number of items to find in the range and only the first ten items need to be retrieved.

Here the performance margin between the two versions was closer than in the previous test. Version 2’s average run speed was 360.94ms while version 3’s runtime was 1336.10ms.

With a smaller number of retrieved items, the version 2 findAll() function did not have to work as hard to collect the methods related to each range it collects. Whereas version 3 still needed to make 10 performance-intensive calls back to the Google Sheet each time with relatively no performance change to test one.

TEST 3: 100 randomised items to find in 50,000. Return first 10 matches using v2-findAll and v3-findNext functions.
TEST 3: 100 randomised items to find in 50,000. Return first 10 matches using v2-findAll and v3-findNext functions.

Test 4: Retrieve the first 50 cells containing the search text where the range contains 100 matching search items.

Predictably, version 2 – findAll() performed the best when the expected match sample is small (100 available matches) and the total first set of cells to retrieve was relatively large (50).

Version 2’s average completion time was 377.13ms compared to version 3’s average of 6552.72ms, performing on average 6175.59ms faster. This is by far the largest margin on performance between the two versions.

Here again, version 3 must perform 50 calls to the Google Sheet, each one retrieving the cell range data. Alternatively, version 2 makes one call to the spreadsheet and then retrieves the cell data for all collected values. This is significantly faster than version 3’s approach.

TEST 4: 100 randomised items to find in 50,000. Return first 50 matches using v2-findAll and v3-findNext functions.
TEST 4: 100 randomised items to find in 50,000. Return first 50 matches using v2-findAll and v3-findNext functions.

Overall

On datasets that may have the potential to contain a large number of matching items, but fewer required results to return, version 3 may be the best option. In all other cases, version 2 is the most optimal approach to finding data in a range.

It is important to note that it can be difficult to accurately measure performance with Apps Script runs because resource allocation to run a script does seem to vary. Nevertheless, with a sample size of 100 runs, it is hoped that average values will be more accurate than a smaller sample.

Grab Your Own Copy of the Google Sheet and Attached Code here

If you have found the tutorial helpful, why not shout me a coffee ☕? I'd really appreciate it.

Looking to learn more about Google Apps Scripts in a more structured format? Udemy has some great courses that can get you from the basics to a real Google Apps Script pro.

Got a more specific problem you need help with, but don’t have the time to develop the skills? Make an enquiry on my 'Hire me!' page. I occasionally pick up projects. Alternatively, Fiverr’s your best bet to find a skilled Google Apps Script developer to solve your problem quickly and professionally. *

*The above affiliate links have been carefully researched to get you to what you specifically need. If you decide to click on one of these links it will cost you just the same as going to the site. If you decide to sign up, I just get a little pocket money to help pay for the costs of running this website.

~Yagi

 

Find first, last & nth value in a Google Sheets range with Apps Script

In this tutorial, we will explore how to find the first and last values in a Google Sheets Range using Google Apps Script. Then we will modify our code to find a value at a specific location. We will then find the position of the first set of values in our Google Sheets range. Lastly, we will create a reusable function to find the first or last set of values in a range.

This tutorial accompanies the YouTube tutorial of the same name:

The starter sheet for the video tutorial:

Starter Sheet

The code for each section of the tutorial can be found below under each section header along with any explanation, where needed.

In our previous tutorial, we covered how to find all values in a Google Sheet, a sheet table or a range. Check it out here:

Find All Values in Google Sheets with Apps Script


The Runsies Function

This is an example function that you can use to run your find functions below. All arguments for the functions below are placed in here along with the execution of the desired function.

In the example below we are running the first function.

 

Find the first value or text in a Google Sheets Range using Apps Scripts FindAll method

In this approach, we make use of our previous tutorial’s script and use the findAll method of the createTextFinder Class.

This method returns an array for each found item that can access the Google Apps Script range class methods.

Line 15 – Once all items in the range are found, we can select the zeroeth item. Incidentally, we could get the last item in the range with this approach by modifying this line to:

const lastVal = foundValue[foundValue.length - 1];

Of course, you would need to update the variable names too.

Line 17 – Here we log the cell position of the first found item using the SpreadsheetApp Range Class getA1Notation method.

Line 19 – Finally to make it easier to test. We set our selected cell value to activate. This makes the cell active and makes it easy for us to crosscheck in our testing. It also has the benefit of navigating the user on the Google Sheet to the desired cell. Check out the image below for an example:

Find first value in a Google Sheets Range with apps script and activate it

Note! This approach can be much, much slower than the next option, particularly if your text finder discovers a lot of cells.

If you have found the tutorial helpful, why not shout me a coffee ☕? I'd really appreciate it.

Find the first value or text in a Google Sheets Range using the iterator method

A much more common approach to finding the first position of the matching value is using the findNext() iterator method of the Text Finder Class.

This is considerably faster on large datasets where you expect to find many occurrences of the found item. Why? Because, the find-all approach will collect all cells containing the value, whereas findNext() will only collect the next value to be found.

Line 13 – Here we replace findAll() with findNext().

Find the last value or text in Google Sheets Range

In this example, we swap the findNext() method with the findPrevious() method.

Interestingly, if we call the find previous method straight after creating the text finder, It will look for the first item starting in reverse order. This means it will start its search from the bottom of the range.

 

Find the position of the nth value in a Google Sheets Range with Apps Script

Here we want to find the nth value in a range. Perhaps the 3rd value or the 10th.

Lines 14-15-  In this function, we return the findAll() method and then identify the position of the value in the selectedVal array.

Line 12 – Note that we will need to subtract one from our position value here before we can use it to find the value in the array. Remember, the array will start at zero.

 

Find the first n values in a Google Sheets Range

In this scenario, we want to find a starting set of values from our range. Maybe we want to grab the top 3 found cells or the first 5.

Line 15 – Here we use the findAll() method again to get a list of all values in the range.

Line 19-29 – Next, we will use a JavaScript ‘for’ loop to iterate over the found cells. We will need to store all the found A1 notation locations in a locations variable on line 19.

Line  25 – On each iteration, we will append the locations with our new cell value.

Line 28 – However, if the index (i) matches the same number as the position variable then we want to break our loop.

 

Find the first or last values of a selected number in a Google Sheets Range

Finally, we have two functions here. Both functions allow you to find either the first set or last set or cells where the search term is found. Their usage really depends upon the type of data that you are working with.

Both functions take 4 arguments:

  1. sheetName – The name of the sheet tab.
  2. text – The text to search.
  3. n – The number of found cells to collect.
  4. reverse (optional) – If true, conduct the search in reverse.

Again, both functions will return an array containing all found cell locations in A1-notation.

Checkout the post below for a detailed benchmark analysis of each function:

Performance of Google Apps Script Text Finder Class on 2 Approaches to Searching Large Datasets

 

Find All Approach

This approach is more performant when you don’t expect to find a lot of matching cells in a large range. It is also suitable if you want to extract a larger list of items starting from the beginning or end of the range.

Why? Because if there are a large number of found variables then the findAll method will take more time to collect the full list of ALL cell locations before we can continue and select the ones we want. Whereas if we use the next option using findNext or findPrevious then each item will be retrieved one at a time, making the second option more performant.

Alternatively, if we want to retrieve say the first 100 items, then the first item would be a better approach. This is because we only make one call to the Google Sheet instead of 100 which is a much slower approach.

Line 16 – Here, we use the findAll() method again.

Line 22 – Note the if-statement here that checks if the reverse parameter is set to true.

Line 24 – If we want to start the search from the bottom of the range, we first set a counter to zero.

Line 25 – Then we run a reverse for loop, starting from the bottom of the found array.

Line 29 – If we find a cell we add it to the locations list like in our previous example.

Lines 31-33 – Finally, we update the counter and then check the counter count against n and break the look if we have a match.

Lines 36 -46 – If there is not reverse argument or the argument is set to false then we want to start our search from the top of the range. Here, we use the same for-loop as the previous chapter.

 

Find Next or Previous Approach

This approach performs better in a large range when there the range contains many found cells, but you may only need to collect only a few of the first or last proceeding items.

Line 15 – To start our search, we only initialise the text finder class.

Line 17 – Set our empty location array.

Line 18 – Creates a counter base on the number (n) of found cell locations that we want to retrieve.

Line 20 – Next, we generate JavaScript while loop to finish once the counter reaches 1. The loop will either find the next or find the previous cell range.

Line 22 – We set the found variable to receive the cell location.

Lines 24-28 – If we have set the item to be reversed we use the findPrevious method and collect each cell location.

Lines 29-34 – Alternatively, we will use the findNext method if reverse is set to false or not included.

Line 36 – Next, we push the cell reference to the locations array.

Line 28 – The last task in the loop is to decrease our counter by one.

Line 43 – Outside our loop, we return the locations array back to the initiating function.

 

If you have found the tutorial helpful, why not shout me a coffee ☕? I'd really appreciate it.

Looking to learn more about Google Apps Scripts in a more structured format? Udemy has some great courses that can get you from the basics to a real Google Apps Script pro.

Got a more specific problem you need help with, but don’t have the time to develop the skills? Make an enquiry on my 'Hire me!' page. I occasionally pick up projects. Alternatively, Fiverr’s your best bet to find a skilled Google Apps Script developer to solve your problem quickly and professionally. *

*The above affiliate links have been carefully researched to get you to what you specifically need. If you decide to click on one of these links it will cost you just the same as going to the site. If you decide to sign up, I just get a little pocket money to help pay for the costs of running this website.

Find All Values in Google Sheets with Apps Script

Just like when using the Ctrl + F shortcut in Google Sheets to find values in your spreadsheet, there is a class in Google Apps Script that can do the same thing.

This could be a useful tool as a part of an automation process. For example, finding the location of a value and applying formatting to it or copying the cell’s entire data into a separate location if the value is a part of a larger text in the cell.

This tutorial accompanies the YouTube video tutorial of the same name.

Grab a copy of the starter sheet to play along and get the most out of the video.

Starter Sheet

Find All Apps Script – Starter Sheet

If you have found the tutorial helpful, why not shout me a coffee ☕? I'd really appreciate it.

The Code

Note that for the video tutorials, I have added the variables (e.g. the Sheet Name, Range) inside each function. It is usually good practice to keep these functions independent and call them from other functions. This makes them more reusable.

Instead, we can add the variables we need as parameters for the functions and return the result. See the example below:

These examples use the TextFinder class as a part of the Google Apps Script Sheets App Class.

In these examples, we use the findAll method of this class. This will return an array containing all the cells containing the selected value searched. From here, you can treat each cell as a range and call range methods like:

  • Get A1 Notation.
  • Get Sheet – Get Name.
  • Get Row.

We use the JavaScript Map method to iterate through each item that we find.

Find All Values in All Sheets

This finds all values in all sheets and returns an array containing an object for each sheet containing the sheet name and the cell location.

Returns:

 

Find All Values in Selected Sheets

Finds all the values in a selected sheet and returns an array identifying the cell that each item is found.

Returns:

[ 'A3', 'A4', 'F14', 'A16' ]

Find All Values in a Selected Range

Finds the values for any item in a selected range and returns the row the item was found on.

Example 1

Returns:

[ 3, 4, 16 ]

Example  2

Returns:

[ 1, 2, 4, 5 ]

The Video

Looking to learn more about Google Apps Scripts in a more structured format? Udemy has some great courses that can get you from the basics to a real Google Apps Script pro.

Got a more specific problem you need help with, but don’t have the time to develop the skills? Make an enquiry on my 'Hire me!' page. I occasionally pick up projects. Alternatively, Fiverr’s your best bet to find a skilled Google Apps Script developer to solve your problem quickly and professionally. *

*The above affiliate links have been carefully researched to get you to what you specifically need. If you decide to click on one of these links it will cost you just the same as going to the site. If you decide to sign up, I just get a little pocket money to help pay for the costs of running this website.

Get the Creator’s Email of a Shared Drive with Google Apps Script

Google Drive’s Shared Drives are designed a little differently than regular Google Drive folders. Each Shared Drive file is collectively owned by the group working on the file or, more directly, the Google Workspace Domain account that manages the file.

While you can search for shared drives and get some level of metadata (e.g. who has what permissions) from them as you can see in this tutorial:

Get a list of Google Shared Drives by ID and Name in Google Apps Script [updated 10 Feb 2022]

… you won’t see details of who created the shared drive with DriveApp or the Drive API advanced service in Google Apps Script.

After a bit of experimentation, I built a solution that uses:

  1. The Drive Activity API to extract the creator’s numerical ID.
  2. The Admin SDK to search for the user by ID and retrieve their email.

Check out the video tutorial below, then grab a copy of the script along with links and a brief discussion of some of the more interesting and technical bits of the code.

The Video

The Code

The main function here is the getSharedDriveCreator() function. If you are just copying and pasting then this will be all you need to add to your project.

All you need to do is add the ID of your shared drive as the first parameter of the function:

getSharedDriveCreator("0APU21xY4hn2STek9PVA")

The runsies() function is just an example function showing how everything works and is not needed in your own project, but may be useful for testing.

You will need to add two Google Apps Script advanced services to your script:

I haven’t changed the reference in either of these services here, but if you do, you will need to update the script.

If you have found the tutorial helpful, why not shout me a coffee ☕? I'd really appreciate it.

Code Walkthrough of the Shared Drive Creator function

Get the activity records of the shared drive

The first task in this script is to invoke the Google Drive Activity API DriveActivity class. You can use this API to:

  • See what has changed on a file or folder.
  • See who made those changes.
  • Provide alerts when changes or comments have been made.

We can create an activity query with the API using  DriveActivity.Activity.query(). The query will return an object containing a historical log of all the interactions on the selected file or folder.

The query takes a single object as a parameter. We are specifying a particular location to run our query so we need to add the “itemName” property.

Strangely the value of the “itemName” needs to contain “items/” and then the file or folder id.

Next, we can filter the returned object down to contain information about the creation of the file or folder. This is achieved with the detail.action_detail_case: field. In these filter fields, the colon (:) is an operator representing “has”. Here we can add “CREATE” to reduce our search to only show information about the creation of the file or folder. Basically, this says:

“In the folder, show me the details related to the creation action.”

This will return an object that looks a little like this:

Getting the Shared Drive creator’s unique id.

If you look down at the actors’ property on line 79 of the object above, you should see only one user, the creator of the shared drive. This will be under “user” > “knowUser” > “personName”.

As you can see, the creator’s email is not provided. We will need to find this in a moment, but first, we need to extract the user’s id from the personName property.

const personName = activity.activities[0].actors[0].user.knownUser.personName

We won’t need the prepended “person/” in the personName value so let’s create a JavaScript substring of just the numerical id.

const accountId = personName.substring(7)

This will result in something like this:

102444833385071164881

Get the user’s details from the Google Admin Directory SDK

With the “users” unique numerical ID we can now use the Google Admin Directory SDK to access some details about the user.

At its most basic level, we can get a user’s details with:

AdminDirectory.Users.get(accountId)

Non-admin privileged users can still make use of the Admin Directory SDK. However, they will be limited to just the information that is publically available. For us, this is no problem, we only want the publically available primary email of our creator.

To ensure that users without admin privileges can run the code without error we need to add an object field to the second parameter of the get request changing the view type to domain public.

"viewType": "domain_public"

Next, we will also set the projection to “basic” to limit the amount of object data returned from the query.

"projection": "basic"

Weirdly, when a user with admin privileges runs code with a “domain public” view type it will result in an error. As such, we need to provide a “Try Catch” statement to handle the times admins run the code.

So, within the catch statement, we can add just the account id to the get method for the admins to access the data.

The resulting object will look a little like this:

Retrieving the email address

Finally, we can collect the primary email of the user with the object path:

user.primaryEmail

Then we return that email back to be used by the function it was instantiated from.

Conclusion

While on the whole, this might be a little bit more of a convoluted process that first expected, the entire processing speed was relatively short.

Try and give this a run-through on your own and then try and get the creator emails of all the shared drives that you have access to by connecting it to the tutorial below:

Get a list of Google Shared Drives by ID and Name in Google Apps Script [updated 10 Feb 2022]

I really like to hear how folk are using and adapting the code that I provide. It provides inspiration for me and the people reading the article. Please consider sharing your use cases in the comments below and subscribe (Top-right sidebar).

Looking to learn more about Google Apps Scripts in a more structured format? Udemy has some great courses that can get you from the basics to a real Google Apps Script pro.

Got a more specific problem you need help with, but don’t have the time to develop the skills? Make an enquiry on my 'Hire me!' page. I occasionally pick up projects. Alternatively, Fiverr’s your best bet to find a skilled Google Apps Script developer to solve your problem quickly and professionally. *

*The above affiliate links have been carefully researched to get you to what you specifically need. If you decide to click on one of these links it will cost you just the same as going to the site. If you decide to sign up, I just get a little pocket money to help pay for the costs of running this website.

~Yagi

%d bloggers like this: