Schedule job remove specific role
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
04-10-2024 11:52 PM
Hello,
I have a requirement that remove specific role of the user through schedule job. Not all roles will remove ex. sn_incident_write, problem_coordinator only this two will remove. Thank you in advance.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
04-11-2024 12:20 AM
Hi @Community Alums
Create a new Scheduled job with script execution:
var roleNames = ['sn_incident_write’, ‘problem_coordinator']; // Define the roles you want to remove
roleNames.forEach(function(roleName) {
// Query to get the sys_id of the role
var roleGr = new GlideRecord('sys_user_role');
roleGr.addQuery('name', roleName);
roleGr.query();
if (roleGr.next()) {
var userRoleGr = new GlideRecord('sys_user_has_role');
userRoleGr.addQuery('role', roleGr.sys_id);
userRoleGr.query();
while (userRoleGr.next()) {
// Delete the user’s role
userRoleGr.deleteRecord();
gs.info('Removed role ' + roleName + ' from user ' + userRoleGr.user.getDisplayValue());
}
} else {
gs.warn('Role ' + roleName + ' not found');
}
});
Please Mark this Helpful and Accepted Solution. If this Helps you to understand. This will help both the community and me..
- Keep Learning
Thanks & Regards
Deepak Sharma
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
04-11-2024 12:26 AM - edited 04-11-2024 12:27 AM
Hello @Deepak Shaerma
Thank you, addition what if the user only removes the specific role when Last login time is last 30 days?
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
04-11-2024 12:53 AM
Hello @Deepak Shaerma
I tried to modify but the query wont work the code applied to all users.
var getUsers = new GlideRecord('sys_user');
var roleNames = ['sn_incident_write','problem_coordinator']; // Define the roles want to remove
getUsers.addQuery('last_login_timeRELATIVELT@dayofweek@ago@30');
getUsers.query();
while(getUsers.next()){
roleNames.forEach(function(roleName) {
// Query to get the sys_id of the role
var roleGr = new GlideRecord('sys_user_role');
roleGr.addQuery('name', roleName);
roleGr.query();
if (roleGr.next()) {
var userRoleGr = new GlideRecord('sys_user_has_role');
userRoleGr.addQuery('role', roleGr.sys_id);
userRoleGr.query();
while (userRoleGr.next()) {
// Delete the user’s role
userRoleGr.deleteRecord();
gs.info('Removed role ' + roleName + ' from user ' + userRoleGr.user.getDisplayValue());
}
} else {
gs.warn('Role ' + roleName + ' not found');
}
});
}