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

BALAJI40
Mega Sage

You can write one Back ground or fix script to achieve that.


amlanpal
Kilo Sage

Hi Bala,



For this you need to use the Background script.


Please activate your elevated privilege (i.e., the 'security_admin' role)-->Navigate to System Definition--> Scripts - Background-->and use the below sample code as per your requirement.



var gr = new GlideRecord('sys_group_has_role');


gr.addEncodedQuery('group.nameLIKEcatalog'); //It fetches all the group which contains 'catalog' in it's name. Please use your requiremnent.


gr.query();


while(gr.next()){


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


gr.update();


}



I hope this helps.Please mark correct/helpful based on impact


Yes bala, its is possible, your code should be like below..


var gr = new GlideRecord('sys_user_group');


gr.addEncodedQuery('group.nameLIKEcatalog'); // if you have any conditon


gr.setLimit(2000);


while(gr.next())


{


var gr1 = new GlideRecord('sys_group_has_role');


gr1.query();


if(gr1.next()){


gr1.group = gr.group;


gr1.role = '282bf1fac6112285017366cb5f867469';   //Pass the sys_id of the role which you want to add


gr.insert();


}


}


Hi balathecharm,



Did you able to have a look at my last response?


If I have answered your question, please mark my response as correct so that others with the same question in the future can find it quickly and that it gets removed from the Unanswered list.


If you are viewing this from the community inbox you will not see the correct answer button.   If so, please review   How to Mark Answers Correct From Inbox View