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 ,

verified , User exists in the System 

@Michael51 

is this happening for all users whose group membership you are trying to remove?

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

@Ankur Bawiskar , yes ankur  , this is happening for all users , had tried with different users 

@Michael51 

when you open that sys_user_grmember record did you check what it shows in xml for that user field value?

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

@Ankur Bawiskar  , user is showing as empty 

<xml>
<sys_user_grmember>
<group display_value="HRIT Operations" name="HRIT Operations">1850953f77e33300d0e310389a106184</group>
<points>0</points>
<scrum_role/>
<sys_created_by>admin</sys_created_by>
<sys_created_on>2023-06-20 08:50:36</sys_created_on>
<sys_id>000849a947632110821f73d7826d4311</sys_id>
<sys_mod_count>0</sys_mod_count>
<sys_updated_by>admin</sys_updated_by>
<sys_updated_on>2023-06-20 08:50:36</sys_updated_on>
<user/>
</sys_user_grmember>
</xml>