使用 Google Admin SDK 中的 google 应用脚本自动创建用户

Automate user creation using google app script in Google Admin SDK

我想在 google 中以管理员身份自动创建用户,我在其中使用应用程序脚本来执行此操作,但是从 documentation 我正在阅读的内容来看,我不太确定我是否我做对了,因为我的代码中出现了一些错误,比如在 POST 之后脚本不工作。

function createUsers() {
  const userjson = {
      "primaryEmail": "atest@example.com",
  "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);
  }
}

根据 official documentation,如果您想使用 Google Apps 脚本执行此操作,您应该按照以下格式设置代码格式:

function createUsers() {
  const userInfo = {
    "primaryEmail": "jvd@domain.com",
    "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}`);
    }
  }  
}

如果您对如何使用用户资源负载有任何疑问,请参阅official documentation of the REST API