Add custom role to all users

Richard Tyler
Tera Expert

i am developing a custom application on my PDI and have created a record producer to use on the service catalog. However, each time a user makes the request, i get an error message 'Requested record not found' . Adding the custom role to the user seems to resole the problem. But my organization has almost 5000 users and as such its not feasible to manually add the role to all users. I used the script below, which seems to add the role with 'empty in the tole field. 

How do i make this work. and dynamically assign the role to all new users (we have LDAP) integration. 

var gr = new GlideRecord("sys_user");

gr.query();

while(gr.next())

{

var role = new GlideRecord('sys_user_has_role');

role.addQuery('user',gr.sys_id);

role.addQuery('role', '<sys_id of Role>');

role.query();

if(!role.next())

{

role.initialize();

role.user = gr.sys_id; role.role = "<sys_id of Role>";

role.insert();

}

}

find_real_file.png

1 ACCEPTED SOLUTION

Abhishek Pidwa
Kilo Guru

If the role needs to be added to every user, I believe you can use this script described in this article:

 

https://docs.servicenow.com/bundle/london-application-development/page/script/useful-scripts/reference/r_AddRoleToEveryUser.html

 

After writing this , you can then schedule this job to run every day after your LDAP integration import. 

 

Please mark this as solved if this solves your problem.

 

Thanks

View solution in original post

6 REPLIES 6

Try this script

//Find a user eg.abc
var gUser = new GlideRecord('sys_user');
gUser.addEncodedQuery('user_name=abc');
gUser.query();
if(gUser.next()){

//Declare roles in array
var arr = ["role1","role2","role3"];

//Assign the roles 
var grd = new GlideRecord('sys_user_has_role');
for(var i =0; i<arr.length; i++){
   grd.initialize();
   grd.user = gUser.sys_id;
   grd.setDisplayValue('role',arr[i]); 
   grd.insert();
 }

}

Richard Tyler
Tera Expert

Thanks Abjishek,

 

This worked perfectly.