Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Script How do I getGivenName() of getActiveUser()

Each user on the domain initiates a simple script we run for leave entitlements but we want the welcome message to be "Hi First Name," however the script doesn't seem to be able to fetch getGivenName() from getActiveUser() for a standard user.

Is there a way?

like image 891
user2097953 Avatar asked Feb 22 '13 04:02

user2097953


People also ask

What is === in Google script?

Equality (==): a == b results in true if the value a is equal to value b. Strict equality (===): a === b results in true if the value a is equal to value b and their types are also the same. Inequality (! =): a !=

How do I change the timezone of a script?

New scripts default to the owner's time zone, but the script's time zone can be changed by clicking File > Project properties in the script editor. Note that spreadsheets have a separate time zone, which can be changed by clicking File > Spreadsheet settings in Google Sheets.

Is there a way to emulate Vlookup in Google script?

Yes, it is possible to emulate many of the built-in functions by using Class Spreadsheet (SpreadsheetApp) and JavaScript Array Object and its methods, but "the emulations" usually will be slower than built-in functions.


1 Answers

As noted in comments, and in Documentation, the UserManager Service is only accessible by Domain Administrators.

Here's an alternative. Domain Users may have themselves in their own contacts, so how about a best-effort attempt at finding themselves there?

/**
 * Get current user's name, by accessing their contacts.
 *
 * @returns {String} First name (GivenName) if available,
 *                   else FullName, or login ID (userName)
 *                   if record not found in contacts.
 */
function getOwnName(){
  var email = Session.getEffectiveUser().getEmail();
  var self = ContactsApp.getContact(email);

  // If user has themselves in their contacts, return their name
  if (self) {
    // Prefer given name, if that's available
    var name = self.getGivenName();
    // But we will settle for the full name
    if (!name) name = self.getFullName();
    return name;
  }
  // If they don't have themselves in Contacts, return the bald userName.
  else {
    var userName = Session.getEffectiveUser().getUsername();
    return userName;
  }
}
like image 50
Mogsdad Avatar answered Oct 13 '22 13:10

Mogsdad