How to automatically remove role from users

susan_stein
ServiceNow Employee
ServiceNow Employee

I need to know how to automatically remove roles from users that haven't logged into the system.

3 REPLIES 3

Mike Allen
Mega Sage

The role-to-user table is sys_user_has_role, so create a background script that queries the sys_user table for any users that have not logged in.   In your while loop, query sys_user_has_role and delete all entries for that user.


edwin_munoz
Mega Guru

Hello Susan,



You can create an Scheduled Job to run a script that removes the role from the users.



Here are the steps that you need to take:



1. Go to Scheduled Jobs, click on the New button


2. Select Automatically run a script of your choosing


3. On run select how often do you want to perform the check


4. Copy paste this code on the script field. Change itil for the role that you want to remove



var users = new GlideRecord('sys_user');


users.addQuery('last_login_time', '<', gs.daysAgo(30));


users.query();




while(users.next()){


      var hasRole = new GlideRecord('sys_user_has_role');


      hasRole.addQuery('user', users.sys_id);


      hasRole.addQuery('role.name', 'itil');


      hasRole.query();


 


      if (hasRole.next()) {


              hasRole.deleteRecord();


      }


}



I would suggest you to test the script first, I haven't tested it yet. You can run this as a background script first to make sure that it would work as expected.



var users = new GlideRecord('sys_user');


users.addQuery('last_login_time', '<', gs.daysAgo(30));


users.query();




while(users.next()){


      var hasRole = new GlideRecord('sys_user_has_role');


      hasRole.addQuery('user', users.sys_id);


      hasRole.addQuery('role.name', 'itil');


      hasRole.query();


 


      if (hasRole.next()) {


              gs.print("The user" + users.name + "has role itil and it is going to be removed");


      }


}


jimvistronix
Kilo Explorer

Susan,



Did you ever try the script Edwin provided and did it work?