How do we remove a role for a user?

sriram9
Giga Contributor

I am working on a script that can remove a role from the users if they qualify certain conditions. like say, if i wanted to remove role ITIL_user for the users who are inactive.

8 REPLIES 8

Tom Alday
Mega Guru

I would look in the sys_user_has_role table, just dot walk to the user's active state 

Archana Reddy2
Tera Guru

Hi Sairam,

Run this script in the background script and it will help you to achieve the requirement.

var gr = new GlideRecord('sys_user');
gr.addQuery('active',false);
gr.query();
while(gr.next())
{
var role = new GlideRecord('sys_user_has_role');
role.addQuery('role','sysid_of_ITILuser');
role.addQuery('user',gr.sys_id);
role.query();
if(role.next())
{
role.deleteRecord();
}
}

Hope this helps.

Mark the answer as Correct/Helpful based on its impact.

Thanks,

Archana

Thank you for the response.  I tried applying this query in scripts background.  But, the role still exists.

Here is the sample code.  I just tweaked this query a little for testing purpose.

 

var gr = new GlideRecord('sys_user');
gr.addQuery('active',true);
gr.addQuery('first_name','Stacey');
gr.query();
while(gr.next())
{
var role = new GlideRecord('sys_user_has_role');
role.addQuery(gr.role,'itil');
role.addQuery('user',gr.sys_id);
role.query();
gs.print("role itil does not exist for the user");
if(role.next())
{
gs.print("role itil exists");
role.deleteRecord();
}
}

Sairam,

Should not use role.addQuery(gr.role,'itil'); since role is not a field in User table(gr object).

If you want to check if role deletion for only Stacey(for now). Use the below.

var gr = new GlideRecord('sys_user');
gr.addQuery('active',true);
gr.addQuery('first_name','Stacey');
gr.query();
while(gr.next())
{
var role = new GlideRecord('sys_user_has_role');
role.addQuery('role','sysid_of_ITILuser'); //sys_id should be given since 'role' is a reference field 
role.addQuery('user',gr.sys_id);
role.query();
if(role.next())
{
role.deleteRecord();
}
}

Mark the answer as Correct/Helpful based on its impact.

Thanks,

Archana