Get All Of The Groups For A User

This script will print all of the groups a member is in, in ServiceNow. Below, we query the [sys_user_grmember] table and find all of the groups where the user field is the sys_id of a …

sys_user_grmember

Buy The "ServiceNow Developer's Manual" Now

We've packed over a decade of ServiceNow Development advice, into a single e-book.

Buy It Now

This script will print all of the groups a member is in, in ServiceNow.

Below, we query the [sys_user_grmember] table and find all of the groups where the user field is the sys_id of a specific user.

In the example below, gs.getUserID() is used for the current user, change this value to be any user’s sys_id.

gs.getUserID(); // returns the sys_id of the logged in user

Here is the full script:

var user = gs.getUserID(); // gets current users sys_id
var gr = new GlideRecord("sys_user_grmember");
gr.addQuery("user", user);
gr.query();

var arr = [];

while (gr.next()) {
    arr.push(gr.group.getDisplayValue())
}

gs.print("All groups: " + arr);

When this is executed, it will print an array of groups that the user is a member of.

You can change this to get the groups of any user, by changing the sys_id of the variable user, in the script to any user’s sys_id.

var user = "5137153cc611227c000bbd1bd8cd2005"; //a sys_id
var gr = new GlideRecord("sys_user_grmember");
gr.addQuery("user", user);
gr.query();

var arr = [];

while (gr.next()) {
    arr.push(gr.group.getDisplayValue())
}

gs.print("All groups: " + arr);

What other related scripts are helpful for ServiceNow Admins?

How would you take this script and improve upon it?

We’d love to hear your thoughts below.



What Do You Think About This Article?

0 0 votes
Article Rating
Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
trackback

[…] Get All Of The Groups For A User […]

1
0
Would love your thoughts, please comment.x
()
x