logo

NJP

Process all of the users in a group...

Import · Apr 14, 2020 · article

Recently I have had to create some scripts that gets all of the user records in a group and update them with some information. In the past I have done a query of the sys_user_grmember table, stored the data in an array and then queryed the sys_user table. So I started looking at a better way to do this so I did not have to do two loops in my code and I came up with using a related list query. I also needed something like this for the Assigned to field of a custom table that was not going to use the assignment group field.

So these two examples will get all of the users in a group but you could have it return all the users in several groups if you wanted.

//Get users based on sys_id of group
var gr = new GlideRecord("sys_user");
gr.addEncodedQuery("^RLQUERYsys_user_grmember.user,>=1,m2m^group=SYS_ID_OF_GROUP^ENDRLQUERY");
gr.query();
while (gr.next()) {
    gs.print(gr.getValue("user_name"));
}

//Get users based on name of group
var gr = new GlideRecord("sys_user");
gr.addEncodedQuery("^RLQUERYsys_user_grmember.user,>=1,m2m^group.name=NAME_OF_GROUP^ENDRLQUERY");
gr.query();
while (gr.next()) {
    gs.print(gr.getValue("user_name"));
}

If you are unsure of the query format you can install the "SN Utils - Tools for ServiceNow" plugin for Chrome or FireFox then you can go to the reporting app in your ServiceNow instance and devise the query using the related list condition. Run the report then double click on the white space at the end of the breadcrumb/filter and a dialog will open that has the query.

ServiceNow has some documentation on Related list querys but its not much.

https://docs.servicenow.com/bundle/orlando-platform-user-interface/page/use/using-lists/concept/c\_EncodedQueryStrings.html

View original source

https://www.servicenow.com/community/developer-articles/process-all-of-the-users-in-a-group/ta-p/2321333