Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

How to remove user from group using Business rules

prakhar_yadav
Tera Contributor

Hi Community,

 

There is a requirement that in "table_1" as soon as "Active" field becomes FALSE, then user in group "crazy_group" should be removed. I think this can be achieved by BR. If you can help me with correct code and conditions I need to place, so that it can be achieved.

 

Thanks

2 REPLIES 2

swathisarang98
Giga Sage

Hi @prakhar_yadav ,

 

You can create before update business rule as below,

I have taken sys_user table and groups,

 

swathisarang98_0-1719415389773.png

 

 

(function executeRule(current, previous /*null when async*/ ) {

    var gr = new GlideRecord('sys_user_grmember');
    gr.addQuery('user', current.sys_id);
    gr.addQuery('group.name', 'Database');//change it to your group name
    gr.query();
    if (gr.next()) {
        //gs.info('group: '+ gr.group.name);
        gr.deleteRecord();
    }

})(current, previous);

 

 

 

Please mark this comment as Correct Answer/Helpful if it helped you.

Regards,

Swathi Sarang

SN_Learn
Kilo Patron
Kilo Patron

Hi @prakhar_yadav ,

 

Please try the below :

It will remove both the roles and users from the group if they are made inactive.

You can update the below addEncodedQuery as per your requirement:

userGrp.addEncodedQuery('active!=true');

 

 

SN_Learn_0-1719417881294.png

  In the advance section, paste the below script:

 

(function executeRule(current, previous /*null when async*/ ) {

    var userGrp = new GlideRecord('sys_user_group');
    userGrp.addEncodedQuery('active!=true');
    userGrp.query();
    while (userGrp.next()) {

        //Remove the member(s) of the group
        var grpMembers = new GlideRecord('sys_user_grmember');
        grpMembers.addQuery('group', userGrp.sys_id);
        grpMembers.query();
        if (grpMembers.next()) {
            grpMembers.deleteMultiple();
        }
        //Remove the role(s) of the group
        var grpRoles = new GlideRecord('sys_group_has_role');
        grpRoles.addQuery('group', userGrp.sys_id);
        grpRoles.query();
        if (grpRoles.next()) {
            grpRoles.deleteMultiple();
        }
    }

})(current, previous);

 

Please mark the answer as correct/helpful based on impact.

 

----------------------------------------------------------------
Mark this as Helpful / Accept the Solution if this helps.