Delete User Roles in bulk

Vamshi_ch123
Tera Contributor

Hi All,

 

I'm trying to delete the roles added by default to the users by using below script in the background but this is not working and not allowing to delete the records

 

var userRole = new GlideRecord('sys_user_has_role');
userRole.addEncodedQuery("sys_updated_onON2024-05-29@javascript:gs.dateGenerate('2024-05-29','start')@javascript:gs.dateGenerate('2024-05-29','end')");
userRole.query();

while (userRole.next()) {
    userRole.deleteRecord();
    gs.print('Deleted role assignment with sys_id: ' + userRole.sys_id);
}

gs.print('Role removal process completed.');
 
Please help
thanks & Regards
6 REPLIES 6

Community Alums
Not applicable

Hi @Vamshi_ch123 ,

 

You can't delete/remove roles which are inherited from the groups.

var userRole = new GlideRecord('sys_user_has_role');
userRole.addEncodedQuery("sys_updated_onON2024-05-29@javascript:gs.dateGenerate('2024-05-29','start')@javascript:gs.dateGenerate('2024-05-29','end')^inherited=False");
userRole.query();
userRole.deleteMultiple();

Here in encoded query I have added a condition to check are not inherited. This will remove user roles which are directly assigned to them.

 

However, if you want to remove the roles which are inherited (from group) you need to remove the user from that group.

 

If my answer helped you in any way, please mark it as helpful or correct.

Hi Sai,

it is showing inherited is true, how to delete these records then

Vamshi_ch123_0-1716955286064.png

Thanks & Regards

Vamshi

Community Alums
Not applicable

@Vamshi_ch123 @Query Group members (sys_user_grmrmber) table and remove/delete the user from that group

Harish Bainsla
Tera Sage
Tera Sage

Hi @Vamshi_ch123  try below code

var userRole = new GlideRecord('sys_user_has_role');
userRole.addEncodedQuery("sys_updated_onONToday@javascript:gs.beginningOfToday()@javascript:gs.endOfToday()");
userRole.query();

if (userRole.hasNext()) {
gs.print('Starting role removal process...');

while (userRole.next()) {
var sysId = userRole.sys_id.toString();

var deleteResult = userRole.deleteRecord();
if (deleteResult) {
gs.print('Deleted role assignment with sys_id: ' + sysId);
} else {
gs.print('Failed to delete role assignment with sys_id: ' + sysId);
}
}

gs.print('Role removal process completed.');
} else {
gs.print('No roles found for the specified date.');
}