Script to Remove role for bulk users under one group
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
03-22-2024 02:29 PM
Hi Guys,
I am looking for background script / fix script to remove more than 2k users who are wrongly assigned with a role ( which is not inherited ) under one of the group. I know ,removing user role, by going to each user record and move the role left to right through slush bucket is tedious job when the users are more.
Can anyone provide me with a script for this ?
Thanks in advance!
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
03-22-2024 02:53 PM
Do the users have the roles because they inherit them from being in a group? Or are the roles assigned to the users directly?
If they have the roles from being in a group, then you would need to target deleting records from the Group Member table (sys_user_grmember). If they are assigned directly then you would need to delete them from the User Has Role table (sys_user_has_role).
I wouldnt recommend using a script though when there are other no/low code solutions such as using Deletion jobs which have built-in rollback functions and are also optimised to delete lots of data quickly compared to a background/fix script.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
03-22-2024 04:51 PM
Below is the sample script you can use:
// Define the group and role from which you want to remove users
var groupName = "YOUR_GROUP_NAME";
var roleName = "ROLE_TO_REMOVE";
// Query for users who are members of the specified group and have the role you want to remove
var group = new GlideRecord('sys_user_group');
if (group.get('name', groupName)) {
var groupMembers = new GlideRecord('sys_user_grmember');
groupMembers.addQuery('group', group.sys_id);
groupMembers.query();
while (groupMembers.next()) {
var user = new GlideRecord('sys_user');
if (user.get(groupMembers.user)) {
// Check if the user has the role you want to remove
var userRoles = new GlideRecord('sys_user_role');
userRoles.addQuery('user', user.sys_id);
userRoles.addQuery('role', roleName);
userRoles.query();
if (userRoles.next()) {
// Remove the role from the user
userRoles.deleteRecord();
gs.info("Role " + roleName + " removed from user: " + user.name);
}
}
}
}
Please Mark ✅Correct if this solves your query and also mark 👍Helpful if you find my response worthy based on the impact.
Thanks