Search code examples
javascriptgoogle-apps-scriptgoogle-admin-sdkgoogle-workspace

How to return if condition from Google's AdminDirectory


I'm trying to return different results for respective google workspace users, the problem I'm facing is... the first answer is returning all users.

E.g. William Tell and John Peter gets the return of Mark Thomas i.e. www.google.com

Expectation: I want to display the answer for respective users.

Where did I go wrong?

function getUserID() {
    var user = Session.getActiveUser().getEmail();
    var name = AdminDirectory.Users.get(user).name.fullName;

    if (name ="Mark Thomas") {
    greeting= "www.google.com";
    } else if (name ="William Tell"){
    greeting = "www.msn.com";
    }
    } else if (name ="John Peter"){
    greeting = "www.yahoo.com";
    }
    return greeting;
    }

Solution

  • Findings:

    • You need to initialize the variable named greeting on your script.

    • You have an extra unnecessary closing bracket on the line before else if (name ="John Peter") statement.

    You may test this tweaked script below:

    Modified script:

    function getUserID() {
       var user = Session.getActiveUser().getEmail();
       var name = AdminDirectory.Users.get(user).name.fullName;
       var greeting; //"greeting" needs to be initialized for the script to work
     
       if(name == "Mark Thomas") {
       greeting= "www.google.com";
       } else if (name == "William Tell"){
       greeting = "www.msn.com";
       } else if (name == "John Peter"){
       greeting = "www.yahoo.com";
       }
     
       return greeting;
       }
    

    Test Result:

    enter image description here

    Suggestion:

    Alternatively, I suggest you use a Switch statement since you have multiple fixed conditions instead of a nested If-Else statement. A switch statement is usually more efficient than a set of nested ifs.

    Script w/ Switch statement:

    function getUserID() {
       var user = Session.getActiveUser().getEmail();
       var name = AdminDirectory.Users.get(user).name.fullName.toString();
       var greeting; //"greeting" needs to be initialized to exist & be used on the script
     
       switch(name){
         case name = "Mark Thomas":
           greeting = "www.google.com";
           break;
         case name = "William Tell":
           greeting = "www.msn.com";
           break;
         case name = "Admin IJG": //Added my test account's full name to see if it works
           greeting = "www.yahoo.com";
           break;
       }
     
       return greeting;
    }
    

    Sample Test Result:

    enter image description here