Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

adding roles to user

sunnysunny
Kilo Contributor

This is the script for adding roles to the user, which I copied from wiki. Can anyone explain what is accumulated_roles here and why we convert this to string?

var gr = new GlideRecord("sys_user");

gr.query();

while(gr.next()) {

  if (gr.accumulated_roles.toString().indexOf(",self_service,") == -1) {

  gr.roles = gr.roles + ",self_service";

  gr.update();

}

}

1 ACCEPTED SOLUTION

Here is the script that   will add self service role to all the active users




var gr = new GlideRecord("sys_user");


gr.addQuery('active', true)


gr.query();




while(gr.next()) {




      var grd = new GlideRecord('sys_user_has_role');


              grd.user = gr.sys_id;


grd.role = '[sys_id of the role you want to add]'; // sys_id of self_service role


grd.insert();




}

View solution in original post

13 REPLIES 13

Here is the script that   will add self service role to all the active users




var gr = new GlideRecord("sys_user");


gr.addQuery('active', true)


gr.query();




while(gr.next()) {




      var grd = new GlideRecord('sys_user_has_role');


              grd.user = gr.sys_id;


grd.role = '[sys_id of the role you want to add]'; // sys_id of self_service role


grd.insert();




}

sunnysunny
Kilo Contributor

ok, how did you get the sys_id of the self_service role?


sunnysunny
Kilo Contributor

Thank you.


Tushar Walveka2
Tera Guru

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();
 }

}