Dynamically Add and Remove Users to/from Group

Bruce11
Giga Expert

Hello,

We are looking to set up a automated process to add users to a specific group and remove them dynamically once or twice a day. Group membership criteria would be:

Active = true
Locked Out = False
Employee Type = Internal or External
Email Ends with "sec.com"

If people qualify they are put in the list, if they do not qualify they are removed. What would be the best way to achieve this with a script? Would appreciate if I can get a sample script for this.

Thank you.

1 ACCEPTED SOLUTION

Hi Bruce,

something like this

var rec = new GlideRecord('sys_user');
rec.addActiveQuery();
rec.addQuery('locked_out', false);
rec.addQuery('employee_type','IN','external,internal');
rec.query();
while(rec.next()){
	if(rec.email.toString().endsWith('sec.com')){
		var gr = new GlideRecord('sys_user_grmember');
		gr.addQuery('user', rec.sys_id);
		gr.addQuery('group.name', 'Group ABC');
		gr.query();
		if(!gr.next()){
			gr.initialize();
			gr.user = rec.sys_id;
			gr.group.setDisplayValue('Group ABC');
			gr.insert();
		}
	}
}

Regards
Ankur

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

View solution in original post

11 REPLIES 11

Hi,

For removing user from group you can do this

1) After update business rule on sys_user table

Condition: Active [Changes To] False

Script: // remove this user from group

For adding the users satisfying your condition to the group you can run schedule job daily

Regards
Ankur

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

One more ask please. Using the criteria, can you provide a scheduled job script sample? Thanks

Hi Ankur,

Thanks for your help. Would it be possible to get a sample of what the scheduled job scrip looks like with the criteria? Thanks

Hi Bruce,

something like this

var rec = new GlideRecord('sys_user');
rec.addActiveQuery();
rec.addQuery('locked_out', false);
rec.addQuery('employee_type','IN','external,internal');
rec.query();
while(rec.next()){
	if(rec.email.toString().endsWith('sec.com')){
		var gr = new GlideRecord('sys_user_grmember');
		gr.addQuery('user', rec.sys_id);
		gr.addQuery('group.name', 'Group ABC');
		gr.query();
		if(!gr.next()){
			gr.initialize();
			gr.user = rec.sys_id;
			gr.group.setDisplayValue('Group ABC');
			gr.insert();
		}
	}
}

Regards
Ankur

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

@Bruce 

Thank you for marking my response as helpful.

If my response helped you please mark it correct to close the question so that it benefits future readers as well.

Regards
Ankur

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader