Can you add users to Groups with script?

gvanroy
Kilo Expert

We are working on addings users to groups based on a field we have for their region. For example all users in the Asia region would be added to the Asia Users group. I haven't seen a way to do this through the ui by picking the group and adding all users that meet the criteria to the group. I know it could be done via the list collector but it limits you to 100 people at a time and when dealing with 8k users its difficult. Because roles/groups are handled differently ie I can't filter from a list view and then update all with the information it would be nice if someone had a similar script to add mass users to groups/roles.

15 REPLIES 15

Mark Stanger
Giga Sage

You can. You just need to insert a record into the Group member table (sys_user_grmember). This sample script queries the user table for any user that has a 'u_region' value of 'Asia'. Then it creates a new Group member record by creating an association with the user and the group called 'Asia group'. You'll probably need to modify this a bit to meet your specific need and you definitely want to be especially careful any time you are working with 8,000 records, but this should be pretty close.



//Query all users in the 'Asia' region
var rec = new GlideRecord('sys_user');
rec.addQuery('u_region', 'Asia');
rec.query();
while(rec.next()){
//Create a new group relationship record for this user
var rec1 = new GlideRecord('sys_user_grmember');
rec1.initialize();
rec1.user = rec.sys_id;
rec1.group.setDisplayValue('Asia Group');
rec1.insert();
}


Worked great! Thanks Mark.


Mark

I just created a post similar to this. Does this script run as a business rule? I want to add a user to a group based on if a user attribute is not null.

Thanks.

Rick


The script I posted previously is meant to do a batch update of user group records. Doing the same thing in a business rule would look something like this...



//Create a new group relationship record for this user
var rec1 = new GlideRecord('sys_user_grmember');
rec1.initialize();
rec1.user = current.sys_id;
rec1.group.setDisplayValue('Asia Group');
rec1.insert();