How to count number of group members in the group? for example "sys_user_group" is the table for group in serviceNow and CABApproval group contain 5 members how can i achieve this with coding

shahebaz1
Kilo Contributor

How to count number of group members in the group? for example "sys_user_group" is the table for group in serviceNow and CABApproval group contain 5 members  how can i achieve this with coding

9 REPLIES 9

The function I posted returns a -1 if the group is not found. It returns a 0 if there are no members (the count of members.)

palmen
Tera Guru

This script should work, can be run as a background script

var gr = new GlideRecord('sys_user_grmember');
gr.addQuery('group', 'Sys ID of CABApproval group');
gr.query();
var count = gr.getRowCount();
gs.log('There are ' + count + ' users in group CABApproval');

Best practice is to use GlideAggregate instead of GlideRecord().getRowCount() if you are just counting records. It's primarily for performance reasons.

While you might not recognize a savings for 5 or 10 records, it's a good habit to get in to using GlideAggregate since you don't know if that 5-10 records will one day be 5-10 million records. getRowCount() will degrade as the list gets bigger whereas GlideAggregate will not.

Fair point

Nikhil Dixit
Giga Expert


Hi there,

You can refer following script in order to achieve your requirement.

var gr = new GlideRecord("sys_user_grmember");
gr.addQuery("group", <sys_id of the group>);
gr.query();
var count= gr.getRowCount();

var getUser = [];
while (gr.next()) {
     getUser.push(gr.user.sys_id);

gs.addInfoMessage("The users are: " +getUser.push(gr.user.sys_id));
    }
}


Please mark answer correct and helpful based on the response.

Regards,

Nikhil Dixit

|www.DxSherpa.com|