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 role to multiple groups

balathecharm
Kilo Expert

I have been asked in an interview how I could add a role to 2000 groups at a time. Can anyone answer me the possible way of doing that??

6 REPLIES 6

Samama Butt
Tera Expert

Hi Bala,

Background Script will help you to accomplish this task.

Navigate to System Definition--> Scripts - Background-->and use the below sample code as per your requirement.

var grp = new GlideRecord('sys_user_group');

grp.addEncodedQuery('sys_idIN Comma Separated sys_ids of groups ); // mention comma-separated sys_ids of groups for which you want to add roles.

//you can also comment above line of code if you want it to be run for all groups.


grp.query();

while(grp.next()){

var gr = new GlideRecord('sys_group_has_role');

gr.Initialize();

gr.group = grp.sys_id;


gr.role = '974381f9538823004247ddeeff7b1267';   //Pass the sys_id of the role which you want to add

gr.insert();

}

 

Please don't forget to mark it correct if it works for you.

AparnaSahu
Tera Guru
Tera Guru

Navigate to System Definition--> Scripts - Background

var gr= new GlideRecord('sys_user_group');
gr.addEncodedQuery('add query here');
gr.query();
gs.info(gr.getRowCount()); //get the row count based on query
while(gr.next()){

var grRole= new GlideRecord('sys_group_has_role');
grRole.initialize();
grRole.group=gr.getUniqueValue();
grRole.role='add sys_id here';
grRole.insert();

}