I want to delete a specific user's role from scripting

Ravi Borade
Giga Contributor

i've tried this but its not working as we can't delete the record even from table ui level 

also tried to switch to security admin and tried to delete it its not working

basically we can't delete this record

var gr = new GlideRecord('sys_user_has_role');
gr.addQuery('user','sys_id of the user');
gr.query();

while(gr.next()){
    gr.deleteRecord();
}
1 ACCEPTED SOLUTION

Naga Ravindra R
Kilo Sage
Hi Ravi,
 
try this below:

var userRole = new GlideRecord('sys_user_has_role');
userRole.addQuery('sys_id', '03ad33e1c08d2300964f80d1691e1a4b'); //Here you need to find which record you want to delete for that user in above table.
userRole.query();
if(userRole.next()){
    userRole.deleteRecord();
}

If my response helps please mark as correct/helpful. šŸ™‚

View solution in original post

7 REPLIES 7

Ankur Bawiskar
Tera Patron
Tera Patron

Hi,

basically you are deleting all roles for that user via script?

Is that script not working fine?

Script looks fine to me

Any Before delete BR on sys_user_has_role is restricting the delete?

Are you running this script in scoped app?

Regards
Ankur

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

Ravi Borade
Giga Contributor

it worked but i used addEncodedQuery() and yess here i was removing all the roles belong to that specific user 

@Ravi Borade 

Thanks for informing.

But the response you marked as correct doesn't relate to your question.

the answer marked as correct won't work for your requirement.

Regards
Ankur

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader