Reputation: 551
I am using Google Apps Script to create users in Google Apps in bulk via spreadsheet
my spreadsheet has 4 columns where i have firstname, lastname, emailId, and password, as these are required to create users.
My following script works fine and create users without issue, however it stops at a point if any user already exists, and does not move forward to attempt other ones in spreadsheet.
I want it to loop through the whole spreadsheet, skip the ones that already exists, and create the ones who don't
Any help is appreciated.
function createUsers() {
var ss = SpreadsheetApp.getActive()
var sheet = ss.getSheetByName("Create Users")
var values = sheet.getDataRange().getValues()
for(i=1; i <values.length; i++)
{
var fName = values[i][0]
var lName = values[i][1]
var email = values[i][2]
var password = values[i][3]
var status = values[i][4]
var user = AdminDirectory.Users.insert({
"primaryEmail": email,
"password": password,
"orgUnitPath": "/MDM Testing",
"name": {
"familyName": lName,
"givenName": fName
}
})
Logger.log(user);
}}
Upvotes: 2
Views: 3458
Reputation: 1226
maybe this auxiliary function can help and it also handles the error when trying to check the email against the directory
function checkIfUserExist(email) {
try {
//get the direcotry
var adminDirectory = AdminDirectory.Users;
//try to retrieve the user with the given email, if this fails an error will be generated
adminDirectory.get(email);
// if no error was generated previously return 1
return 1;
} catch (e) { //if the attempt to get the user cause an error
//if the error says not found
if (e.message.indexOf('Not Found') !== -1) {
//return 0
return 0;
} else {
//if the error does not include a not found text, something else happened
console.log("ERROR: " + e.message);
}
}
}
sources checked: https://developers.google.com/admin-sdk/directory/reference/rest https://developers.google.com/admin-sdk/directory/reference/rest/v1/users/get
Upvotes: 0
Reputation: 1
Use
var userFromDirectory = AdminDirectory.Users.list.name
instead of
var userFromDirectory = AdminDirectory.Users.get(email);
Upvotes: -1
Reputation: 2622
You can add If condition to check duplicate user as follows.
function createUsers() {
var ss = SpreadsheetApp.getActive()
var sheet = ss.getSheetByName("Create Users")
var values = sheet.getDataRange().getValues()
for(i=1; i <values.length; i++)
{
var fName = values[i][0]
var lName = values[i][1]
var email = values[i][2]
var password = values[i][3]
var status = values[i][4]
// Check user exist or not by email address.
var userFromDirectory = AdminDirectory.Users.get(email);
if(email != userFromDirectory.primaryEmail){
var user = AdminDirectory.Users.insert({
"primaryEmail": email,
"password": password,
"orgUnitPath": "/MDM Testing",
"name": {
"familyName": lName,
"givenName": fName
}
})
Logger.log(user);
} // end of if
}}
Upvotes: 1