Background script to add role to users with certain queries not working

Marissa N_
Kilo Expert

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!

1 ACCEPTED SOLUTION

RAHUL YADAV9
Mega Guru

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.

View solution in original post

7 REPLIES 7

Musab Rasheed
Tera Sage
Tera Sage

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();
}

 

Please hit like and mark my response as correct if that helps
Regards,
Musab

SumanthDosapati
Mega Sage
Mega Sage

Hi @Marissa N. 

In your fourth line, 

Just replace 'CONTAINS' with 'LIKE'.

 

Regards,

Sumanth

Jaspal Singh
Mega Patron
Mega Patron

@Marissa N. good to know you got what was expected but as an ideal practice better is to map User to Group instead of mapping User to Role directly