getMyGroups() not working properly.

KS86
Tera Contributor

Hi all,

 

I am using getMyGroups() in my code to get all groups. It is returning one extra group. Why?

KS86_0-1766504083110.png

 

I know below thing can be achieved by other ways, but I want to use getMyGroups().

 

My code-

var groups = gs.getUser().getMyGroups();
var groupIds=JSON.parse(JSON.stringify(groups));
var gr=new GlideRecord('sys_user_group');
gr.addQuery('sys_id', 'IN', groupIds);
gr.query();

while(gr.next()){
    gs.info("Name "+gr.name)
}

Answer-
*** Script: Name HR Tier 1
*** Script: Name App Engine Admins
*** Script: Name Conditional Script Writer
*** Script: Name Team Development Code Reviewers
*** Script: Name HR
2 REPLIES 2

KS86
Tera Contributor

All these groups don't have Parent except HR Tier 1 , it is a child of HR group.

Ankur Bawiskar
Tera Patron
Tera Patron

@KS86 

getMyGroups() returns parent group as well for the child to which you belong

So you should query sys_user_grmember to get exact group to which you belong

var groups = [];
var gr = new GlideRecord('sys_user_grmember');
gr.addQuery('user', 'IN', gs.getUserID());
gr.query();
while (gr.next()) {
    groups.push(gr.group.name.toString());
}
gs.info('groups are' + groups.toString());

💡 If my response helped, please mark it as correct and close the thread 🔒— this helps future readers find the solution faster! 🙏

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