How do we remove a role for a user?
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎05-09-2018 04:18 AM
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.
- Labels:
-
Scripting and Coding
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎05-09-2018 10:48 AM
I would look in the sys_user_has_role table, just dot walk to the user's active state

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎05-09-2018 11:59 AM
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
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎05-10-2018 02:19 AM
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();
}
}

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎05-10-2018 02:33 AM
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