Background Script - to remove roles from users

Lucy10
Tera Contributor

Hi,

I need assistance to remove a role from multiple users. I have got a list of the users that need to retain the role, but I don't have an option of "is not one of" to build a query for an encoded list.

any recommendation on the best way?

 

Thanks,

 

L

5 REPLIES 5

Jaspal Singh
Mega Patron
Mega Patron

Hi Lucy,

 

Ideally it should be Role to Group & Group to Member association instead of direct Role to User association.

However, you can follow link for all possible options that server as alternative for 'is not one of'

Brad Bowman
Kilo Patron
Kilo Patron

Hi Lucy,

If you haven't already done so, check the Roles related list on some of the user records who have this role to determine if it was granted to the user, or if it is inherited from a group (best practice).

You can use an encoded query like this on the sys_user_has_role table to return the records for this role where the role is not inherited, and the user isn't one of the few exceptions listed

inherited=false^role=7fcaa702933002009c8579b4f47ffbde^user!=ae2b5deadb1c9010a918196c29961989^user!=8ff5b254b33213005e3de13516a8dcf7

If the role is inherited, or if there's a mix, this encoded query on sys_user_grmember will return the records for members of the specified group that are not one of the few exceptions listed, then you would run this for each group that has this role.

group=0a52d3dcd7011200f2d224837e6103f2^user!=46d44a23a9fe19810012d100cca80666^user!=62826bf03710200044e0bfc8bcbe5df1

Ankur Bawiskar
Tera Patron
Tera Patron

Hi,

you can form your query as below using NOT IN operator

ensure the user sys_id you want to retain are in this array; rest all records would be deleted

var arr = ['01a87c99dbf0bf00db9b9875db9619b7','1422cd36db64f700db9b9875db96199a'];
var gr = new GlideRecord('sys_user_has_role');
gr.addQuery('user.sys_id', 'NOT IN', arr);

// comment this after testing

gr.setLimit(5); // first test for few records
gr.query();

gr.deleteMultiple();

Mark Correct if this solves your issue and also mark 👍 Helpful if you find my response worthy based on the impact.
Thanks
Ankur

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

Thank you! what about NULL values?