- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎06-03-2022 01:48 AM
I am trying to add a role to a specific group of users. These users all need to be active, and part of a specific company. The script is not erroring, but it's also not adding the role. What am I doing wrong? Another similar script executed earlier on the Contacts table worked well.
var gr = new GlideRecord("sys_user");
gr.addQuery('active', true);
gr.addQuery('company', 'CONTAINS', 'companyname'); //we have multiple companies, but all contain a specific word.
gr.query();
while(gr.next()) {
var role = new GlideRecord('sys_user_has_role');
role.addQuery('user',gr.sys_id);
role.addQuery('role', '7fcaa702933002009c8579b4f47ffbde');
role.query();
if(!role.next())
{
role.initialize();
role.user = gr.sys_id;
role.role = "7fcaa702933002009c8579b4f47ffbde";
role.insert();
}
}
Thank you in advance for the help!
Solved! Go to Solution.
- Labels:
-
Scripting and Coding
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎06-03-2022 02:03 AM
I made some corrections. Please check now.
var gr = new GlideRecord("sys_user");
gr.addQuery('active', 'true');
gr.addQuery('company', 'LIKE', 'companyname'); //we have multiple companies, but all contain a specific word.
gr.query();
while(gr.next()) {
var role = new GlideRecord('sys_user_has_role');
role.addQuery('user',gr.sys_id);
role.addQuery('role', '7fcaa702933002009c8579b4f47ffbde');
role.query();
if(!role.next())
{
role.initialize();
role.user = gr.sys_id;
role.role = "7fcaa702933002009c8579b4f47ffbde";
role.insert();
}
}
Feel free to mark correct and helpful.

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎06-03-2022 02:14 AM
Hello,
Always try to use encoded query, your query for company doesn't look correct try below code and see if that works.?
var gr = new GlideRecord("sys_user");
gr.addEncodedQuery('active=true^companyLIKEcompanyname');
gr.query();
while(gr.next()) {
var role = new GlideRecord('sys_user_has_role');
role.addQuery('user',gr.sys_id);
role.addEncodedQuery('role!=7fcaa702933002009c8579b4f47ffbde');
role.query();
if(role.next())
{
role.initialize();
role.user = gr.sys_id;
role.role = "7fcaa702933002009c8579b4f47ffbde";
role.insert();
}
Regards,
Musab

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎06-03-2022 02:20 AM
Hi
In your fourth line,
Just replace 'CONTAINS' with 'LIKE'.
Regards,
Sumanth

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎06-03-2022 02:28 AM