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

Would the BR when=after and insert? We would like to make it so when a user is created and the 'company' is not 'X value' add them to a specific group.

Thanks


Yes. With that scenario you would want an 'After insert' business rule.


Any assistance on this would be appreciated.

Name: Add to Group...
Table: User [sys_user]
When: after
Insert: True
Active: True
Condition: (issue here... trying to examine the users 'company' and we want it to be if it does not equal X then the script should insert them into the Y group)
Script:
var rec1 = new GlideRecord('sys_user_grmember');
rec1.initialize();
rec1.user = current.sys_id;
rec1.group.setDisplayValue('Y group');
rec1.insert();


You can get the current user company sys_id like this...



gs.getUser().getCompanyID();


So your condition would look like this...


gs.getUser().getCompanyID() != 'sys_id_of_company_record'


You might want to base this on the name of the company though. If that's the case then you could do something like this I think.


gs.getUser().getCompanyRecord().name != 'Name of your company here'


See this post for a listing of all of the common user-related functions like this...
http://www.servicenowguru.com/scripting/user-object-cheat-sheet/


Thanks we got this to function but had one other snafu that we are hoping the community can shed some light on. The addition of a user with X company will perform the business rule actions when using the admin role but it will not work when we have it with another role, ITIL for example. We have allowed some of our support personnel to added customers if they are not already in the system. If they add a person it does not insert/create the customer in the group. We also set the role to write/create on sys_user_grmember (along with user_admin by default).