Script to Remove role for bulk users under one group

Sndeveloper Adm
Tera Guru

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!

2 REPLIES 2

graham_c
Tera Guru

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.

Maddysunil
Kilo Sage

@Sndeveloper Adm 

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