How to get all the groups a user is in ?

Hrishabh Kumar
Giga Guru

I have sys_id of a user and I need to get the list of groups in which the is user present.

I need to achieve this via Script.

1 ACCEPTED SOLUTION

Harshal Aditya
Mega Sage
Mega Sage

Hi @Hrishabh Kumar ,

 

Hope you are doing well.

 

Please try below code -

 

var getGroup = new GlideRecord("sys_user_grmember");
getGroup.addQuery("user","user sys_id");
getGroup.query();
gs.log(getGroup.getRowCount());
while(getGroup.next()){
gs.log(getGroup.group.name);
}

 

Please mark this response as correct or helpful if it assisted you with your question.

Regards,
Harshal

View solution in original post

6 REPLIES 6

Hii @Harshal Aditya,

I am having a requirement of to populate only those groups which user is part of it and user is basically having a field on Knowledge form their referencing the sys_user, based upon that user the respective groups only visible it on ownership (reference) field.

 

Hope you will provide me the better solution!

 

Amit Gujarathi
Giga Sage
Giga Sage

Hi @Hrishabh Kumar ,
I trust you are doing fine.
To get the list of groups in which a user is present, you can use a GlideRecord query to search for all the group membership records that match the user's sys_id. Here's an example script:

var userSysId = 'insert_user_sys_id_here';
var groupMembers = [];

// Query for all the Group Membership records where the user is a member
var gr = new GlideRecord('sys_user_grmember');
gr.addQuery('user', userSysId);
gr.query();

// Iterate through the records and add the group names to the array
while (gr.next()) {
  var groupName = gr.group.getDisplayValue(); // Get the display value of the Group field
  groupMembers.push(groupName);
}

// Log the array of group names
gs.log(groupMembers);

Was this answer helpful?


Please consider marking it correct or helpful.


Your feedback helps us improve!


Thank you!


Regards,


Amit Gujrathi