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

Frank1975
Kilo Guru

Hi Daniel, 

i guess the unique part here is the user name. 

Do a Glide query on the sys_user table to see if you can find this user 

if not , run your script, 

if yes, return. 

 

Let me know if that helps.

Frank

Shishir Srivast
Mega Sage

May be you can try something like below,

 

var gr = new GlideRecord('sys_user');
if(!gr.get('email', email.body.ss_email)){
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();
}

I haven't tried this yet - I tried the last suggestion in the thread first and it worked very nicely.  I will try this too and will see, thank you so much!

Sure, thanks for the update. this should help you too.