Add or remove member from the group

Michael51
Tera Guru

Hello All,

I have an requirement to Automate request for Add or remove member to group Item ,  we have two list collector fields 

one is for Adding members and the other one for removing members , here my challenge is sometimes if user is already included in the group we need to Auto complete the request by adding work notes as "request already exists " in the group  , need your help in understanding how we can tackle this Scenario 

 

I have following script for adding and removing members from the group for run script 

var group = current.variables.group_name;

var usersToAdd = current.variables.addmemberlist; // give correct variable name here

var usersToRemove = current.variables.removememberlist;
 
var grp1 = new GlideRecord('sys_user_grmember');
grp1.addQuery('group',group);
grp1.addQuery('user',usersToRemove);
grp1.query();
while(grp1.next())
{
grp1.deleteMultiple();
}

var arr = usersToAdd.toString().split(',');

for (var i = 0; i < arr.length; i++) {
    var addRec = new GlideRecord('sys_user_grmember');
    addRec.addQuery("user", arr[i]);
    addRec.addQuery("group", group);
    addRec.query();
    if (!addRec.hasNext()) {
        gs.info("getting into if loop");
        addRec.initialize();
        addRec.user = arr[i];
        addRec.group = group;
        addRec.insert();
    }
}

can you please give some suggestion how we can develop this kind of automation 

@Ankur Bawiskar @jaheerhattiwale 

25 REPLIES 25

@Ankur Bawiskar  Am using this in run script activity and am trying to remove user from group who is already exists in the group , it is removing user but it is showing as empty, this logic should work like it should completely remove from the group without that empty as well

@Ankur Bawiskar , hope you got what is my requirement now?

@Michael51 

are you still seeing records in sys_user_grmember for that user for those groups?

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

hi @Ankur Bawiskar  , am trying to remove an existing user from total rewards group and below is the output 

Michael51_0-1687247631374.pngMichael51_1-1687247651480.png

 

@Michael51 

the screenshot shows the user field is empty so possibly that user is not present in the instance.

Did you check if that user is present in user table?

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