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!