0

I want to automate user creation in google as an Admin where I use app script to do it, however from the documentation I'm reading I'm not quite sure if I'm doing it right since I'm getting some errors in my code, like after POST and the Script not working.

function createUsers() {
  const userjson = {
      "primaryEmail": "[email protected]",
  "name": {
    "givenName": "afirstName",
    "familyName": "alastName"
  },
  "suspended": false,
  "password": "pass2022",
  "hashFunction": "SHA-1",
  "changePasswordAtNextLogin": true,
  "ipWhitelisted": false,
  "orgUnitPath": "myOrgPath",
  };

  const optionalArgs = {
   customer: 'my_customer',
   orderBy: 'email'
  };

  POST https://admin.googleapis.com/admin/directory/v1/users

  try {
    const response = AdminDirectory.Users.list(optionalArgs);
    const users = response.users;

    //check if user exists
    if (!users || users.length === 0) 
    //create new user
    return AdminDirectory.newUser(userjson);

    // Print user exists
    Logger.log('User Existing');
    
  } catch (err) {
    // TODO (developer)- Handle exception from the Directory API
    Logger.log('Failed with error %s', err.message);
  }
}
4
  • 1
    Try removing the line POST https://admin.googleapis.com/admin/directory/v1/users. Commented May 18, 2022 at 9:46
  • 1
    What are the errors? Commented May 18, 2022 at 9:47
  • i tried removing https and it executes, however it does not create a new user Commented May 18, 2022 at 9:49
  • Have you enable the advanced service? Have you tried the code sample in the official docs -> developers.google.com/apps-script/advanced/admin-sdk-directory? Commented May 18, 2022 at 13:51

1 Answer 1

1

As per the official documentation, if you want to do it with Google Apps Script, you should format your code as follows:

function createUsers() {
  const userInfo = {
    "primaryEmail": "[email protected]",
    "name": {
      "givenName": "Jackie",
      "familyName": "VanDamme"
    },
    "suspended": false,
    "password": "thisisasupersecret",
    "changePasswordAtNextLogin": true,
    "ipWhitelisted": false
  };
  try{
    AdminDirectory.Users.insert(userInfo);
    console.log("User added");
  } catch(error){
    const {code, message} = error.details;
    if(code === 409 && message === "Entity already exists."){
      console.log("User already exists");
    } else {
      console.log(`${code} - ${message}`);
    }
  }  
}

If you have any doubts about how to use the user resource payload, please refer to the official documentation of the REST API.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.