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

Deepshikha 3010
Mega Guru

Hii Bruce,

you can use workflow run script to add/remove users

you can used script include with advance reference qualifier on "user" variable

 

javascript: new AddRemove_user().filter(current.variables.group);

var AddRemove_user = Class.create();
AddRemove_user.prototype = Object.extendsObject(AbstractAjaxProcessor, {
filter: function(group){

var Buildusers = ' ';
var usr = new GlideRecord('sys_user_grmember');
usr.addQuery('group',group);
usr.query();
while(usr.next()) {
if (Buildusers.length > 0) {
//build a comma separated string of users if there is more than one
Buildusers += (',' + usr.user);
}
}
var result = 'sys_idNOT IN' + Buildusers;
//var result = "";
return result;
},

type: 'AddRemove_user'
});

 

in workflow run script used 

1. Dynamic group approval:
answer.push(current.variables.group.manager);
2. Run Script :
var gr = new GlideRecord('sys_user_grmember');
gr.initialize();
gr.user=current.variables.user;
gr.group=current.variables.group;
gr.insert();

 

Regards,

Deepshikha Pandey

 

If my answer helped you in any way, please then mark it as helpful.

Hi Deepshikha,

This is not for a catalog item so I am not sure I can use the workflow option. We are adding this group to enable users in it view dashboard.

Can I use just the script include to achieve this? What do I add to the advance ref qualifier to achieve this?