how to create user using background script?

sureshs3
Tera Contributor

how to create user using background script? using below conditions.

1> First we need to check if users exist or not, if user is exist not need to create and just update the role.

2> If users not exist then user has to create in users table and update the role/

1 ACCEPTED SOLUTION

Shamma Negi
Kilo Sage
Kilo Sage

Use this script:

 

var user = new GlideRecord("sys_user");

user.addQuery("sys_id", user); // user is a variable which has a sys_id of the user which needs to be checked whether it exist or not

user.query();

if(user.next())

{

//update user roles

var roles = new GlideRecord("sys_user_has_role");

roles.initialize();

roles.roles = "282bf1fac6112285017366cb5f867469" // itil role sys_id

roles.user = user.sys_id;

roles.insert();

}

//else create a user record if user doesnt exist

 

var user1 = new GlideRecord("sys_user");

user1.initialize();

user1.user_name= username; // username is the variable which has the username of the new user

user1.first_name = user_firstname;

user1.insert();

 

See if this helps you!

 

Regards,Shamma Negi

View solution in original post

3 REPLIES 3

Johns Marokky
Tera Guru

Hi @sureshs3 ,

can you explain in detail what fields we get in the payload? (like user name, First Name, last Name, email id, etc).

If you could post a sample it would be great in helping to build out the scripts.

 

Regards,

Johns

We need User ID, First Name, Last Name details to be update and Password needs reset filed to be set active.

and any role to be added to user profile.

Shamma Negi
Kilo Sage
Kilo Sage

Use this script:

 

var user = new GlideRecord("sys_user");

user.addQuery("sys_id", user); // user is a variable which has a sys_id of the user which needs to be checked whether it exist or not

user.query();

if(user.next())

{

//update user roles

var roles = new GlideRecord("sys_user_has_role");

roles.initialize();

roles.roles = "282bf1fac6112285017366cb5f867469" // itil role sys_id

roles.user = user.sys_id;

roles.insert();

}

//else create a user record if user doesnt exist

 

var user1 = new GlideRecord("sys_user");

user1.initialize();

user1.user_name= username; // username is the variable which has the username of the new user

user1.first_name = user_firstname;

user1.insert();

 

See if this helps you!

 

Regards,Shamma Negi