script add a role to a User

Ha Le
Tera Expert

I want to write script to add a role to a User, thanks 

5 REPLIES 5

Voona Rohila
Kilo Patron
Kilo Patron

Hi Ha Le

You can add role to user manually, what is the requirement?

 

sample code:

Map role sys_id,user sys_id accordingly.

var grSysUserHasRole = new GlideRecord('sys_user_has_role');
    grSysUserHasRole.initialize();
    grSysUserHasRole.setValue('user' ,'user_sysid');
    grSysUserHasRole.setValue('role','role_sysid');
    grSysUserHasRole.insert();

Mark it helpful if this helps you to understand. Accept solution if this give you the answer you're looking for
Kind Regards,
Rohila V
2022-25 ServiceNow Community MVP

i want to add role admin for user itil 

seem like above not work 

Anshu_Anand_
Kilo Sage
Kilo Sage

As a best practice you should add user to a group rather than giving the role directly .

var gr = new GlideRecord("sys_user_grmember"); // group member
gr.initialize();
gr.group ='Analysts';
gr.user='Paul Martin';
gr.insert();

Hope its helpful

Regards,
Anshu