The CreatorCon Call for Content is officially open! Get started here.

Adding roles in bulk

jared_wentzel
Kilo Contributor

I'm trying to add a role to all users who have a certain value for company. So I found the following wiki page script and I am trying to modify it but first of all I'm not sure where to put it for a one time on demand run. I trying putting in in a scheduled job, and a client script with no dice...

http://wiki.servicenow.com/index.php?title=Useful_User_Scripts

And here is my script...

var gr = new GlideRecord("sys_user");

gr.addQuery('company', 'Fulbright & Jaworski L.L.P.');

gr.query();

while(gr.next()) {

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

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

    gr.update();

}

1 ACCEPTED SOLUTION

company is a related record on the user form so you will need to use the sys_id of the company



change


gr.addQuery('company', 'Fulbright & Jaworski L.L.P.');




to




gr.addQuery('company', 'sys_id of the company');


View solution in original post

20 REPLIES 20

jared_wentzel
Kilo Contributor

So would basically have to add both of these scripts into one some how?


jared_wentzel
Kilo Contributor

Alright I put together the following script, It's not working but am I at least getting warmer???



AddUSRoleTest.JPG


I think that should work to be honest, the other thing I might try is just doing the role check in a separate function so you can just return if you find the role...



var gr = new GlideRecord('sys_user');


gr.addQuery('company','company_sys_id');


gr.query();


while (gr. next()){


gs.log('checking for role against user ' + gr.user_name);


checkuserhasrole();


}



function checkuserhasrole(){


    var myrole= new GlideRecord("sys_user_has_role");


          myrole.addQuery("user", gr.sys_id);


          myrole.addQuery("role", 'b1e8e21b643521006601c2c80d6c04bf');


          myrole.query();


          if (myrole.next()) {


                gs.log(" already has the group_admin role for the group - not adding");


return;


          } else {


gs.log('cannot find user with role so adding ');


                myrole.initialize();


                myrole.user = gr.sys_id;


                myrole.role = 'b1e8e21b643521006601c2c80d6c04bf;


                myrole.insert();


                      }


}


Hi mguy,


can u please tellme what is the role of accumulated_roles field? where does it get its value populated from?


thanks,


ramya


jared_wentzel
Kilo Contributor

The final script I had posted an image of was correct like you said, I just had to confirm the Sys_IDs... talk about tedious stuff!! But I'm getting there