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

Oh duh... Never mind, let me give it a shot! Thank you!


jared_wentzel
Kilo Contributor

Nope... Still no luck! Why can't there be an easier way to add roles to a user based of a value they have? This program is unnecessarily difficult for mundane tasks...I understand it is very powerful and can do a whole lot, but when it comes to doing everyday (should be simple) tasks it's just overly complicated.


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');


marcguy
ServiceNow Employee
ServiceNow Employee

fyi, whenever I want to build a query and i'm not quite sure, I build the query in the UI and then when I'm happy right-click on the blue breadcrum and choose 'COPY QUERY'



this will give you the query in this string, so at least you know when you have to use sys_ids or values:


company=6613255e6fc4c500c60337c64f3ee426



or you could just change your line to addEncodedQuery('company=6613255e6fc4c500c60337c64f3ee426'); and use that.


harikrish_v
Mega Guru

Hi Jared,



Try this:-



var user = new GlideRecord("sys_user");


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


user.query();


while(user.next()) {


  var myrole = new GlideRecord('sys_user_has_role');


myrole.initialize();


  myrole.user = user.sys_id;


  myrole.role.setDisplayValue('your_role_name');


  myrole.insert();


}


I have basically modified the code from above a little bit, this should work. Also I am assuming that the name of your role is unique, if there are multiple roles with the same name, this code wont work.



Thanks & Regards,


Hari