How to add multiple users to a group and remove multiple users from a group using run script in workflow ? i tried many scripts but that didn't work please help and thank you

DEXTER RG
Tera Contributor

find_real_file.png

1 ACCEPTED SOLUTION

i have updated both the script try now and validate with log

View solution in original post

5 REPLIES 5

Harsh Vardhan
Giga Patron

in what scenario you want to add and want to remove the users?

you want to add or remove the users from the same run script activity? 

 

sample script to add multiple users to single group.

 Updated SCript

var usrAddArray = current.variables.<your list collector users variable>.toString();
usrAddArray = usrAddArray.split(',');

// loop through array and add users to the group
for (var i =0; i < usrAddArray.length; i++) {
	var sys_id = usrAddArray[i];
	if (sys_id != ''){
		var grpToAdd = new GlideRecord('sys_user_grmember');
		grpToAdd.addQuery('group', current.variables.<group variable name>);
		grpToAdd.addQuery('user', sys_id);
		grpToAdd.query();
		if (grpToAdd.next()){
			//already in group
			gs.log('***** User sys_id: ' + sys_id + ' already in group: ' + current.variables.<group variable name>.name);
		} else {
			grpToAdd.initialize();
			grpToAdd.group = current.variables.<group variable name>;
			grpToAdd.user = sys_id;
			grpToAdd.insert();
			workflow.debug('***** User sys_id: ' + sys_id + ' added to group: ' + current.variables.<group variable name>.name);
		}
	}
}

 

by using same logic you can remove the multiple users from the group..

example:

 



var usrRemoveArray = current.variables.<list collector user variable name>.toString();
usrRemoveArray = usrRemoveArray.split(',');

// loop through array and add users to the group
for (var i =0; i < usrRemoveArray.length; i++) {
	var sys_id = usrRemoveArray[i];
	if (sys_id != ''){
		var grpToRemove = new GlideRecord('sys_user_grmember');
		grpToRemove.addQuery('sys_id', sys_id);
		grpToRemove.query();
		if (grpToRemove.next()){
			
			grpToRemove.deleteRecord();
			gs.log('***** sys_user_grmember sys_id: ' + sys_id + ' deleted from group: ' + current.variables.<group name>.name);
		} else {
			gs.log('***** sys_user_grmember sys_id: ' + sys_id + ' not in group: ' + current.variables.<group variable>.name);
		}
	}
}

DEXTER RG
Tera Contributor

THANKS A LOT HARSH ADDING SCRIPT IS WORKING PERFECTLY BUT THE REMOVE SCRIPT IS DIDN'T WORKING AS EXPECTED...CAN YOU PLEASE PROVIDE ME ANY OTHER SOLUTION THANKS AGAIN HARSH.

can you just try to change this line

 

grpToRemove.query('sys_id', sys_id);

 to

grpToRemove.addQuery('sys_id', sys_id);

you need to put log and see why it's not working in your scenario .

 

might be you are missing some small things in your script.

i have updated both the script try now and validate with log