How can I check to see if a user exists before creating a new user?

Daniel Shock
Kilo Sage

This community has been great and I have been able to figure out the following script to create a new user in an inbound action:

var newUser = new GlideRecord('sys_user');
newUser.initialize();
newUser.user_name = email.body.ss_email;
newUser.first_name = email.body.ss_fn;
newUser.last_name = email.body.ss_ln;
newUser.email = email.body.ss_email;
newUser.insert();

 

That works just as I had hoped.  However, I need to query the user table before the new user is created so that I don't end up with duplicates.  I would like to search the user table for the email address and verify that it is not attached to any user.  If not, then create the new user.  If it exists, then skip.

I have found pieces to the answer but not enough to get me there.  Any help would be appreciated!

 

thanks!

 

Daniel

1 ACCEPTED SOLUTION

Patrick DeCarl1
ServiceNow Employee
ServiceNow Employee

Try below code. 

 

var newUser = new GlideRecord('sys_user');
newUser.addQuery('email', email.body.ss_email); //change to whatever is going to be unigue value
newUser.query(); 
if (!newUser.next()) { // if query doesnt return a match, create account, if we do see an user we do nothing
    newUser.user_name = email.body.ss_email;
    newUser.first_name = email.body.ss_fn;
    newUser.last_name = email.body.ss_ln;
    newUser.email = email.body.ss_email;
    newUser.update();
}

View solution in original post

7 REPLIES 7

Patrick DeCarl1
ServiceNow Employee
ServiceNow Employee

Try below code. 

 

var newUser = new GlideRecord('sys_user');
newUser.addQuery('email', email.body.ss_email); //change to whatever is going to be unigue value
newUser.query(); 
if (!newUser.next()) { // if query doesnt return a match, create account, if we do see an user we do nothing
    newUser.user_name = email.body.ss_email;
    newUser.first_name = email.body.ss_fn;
    newUser.last_name = email.body.ss_ln;
    newUser.email = email.body.ss_email;
    newUser.update();
}

This worked immediately!  Thank you so much!

Maybe you can help me here. I just spent two hours banging my head against the wall by using this code, only to find the query was not matching, the responseBody from the API was long and the field data length was short so although they were the same in theory, they were not equaling out. 

 

My question is this: where in ServiceNow can you log that actual query to see if the information matches or if it comes back false?

 

Thanks,

 

Steve