Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

Schedule job remove specific role

Community Alums
Not applicable

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.


3 REPLIES 3

Deepak Shaerma
Kilo Sage
Kilo Sage

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


Community Alums
Not applicable

Hello @Deepak Shaerma 

Thank you, addition what if the user only removes the specific role when Last login time is last 30 days?

Community Alums
Not applicable

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');
    }
});
}