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.

How to remove groups from user profile if last login is last 3 months

Nani18
Tera Contributor

Hello Experts,

 

My requirement is ...

If any user last login time is before 3 months then we need to remove all groups from user profile except one ABC group.

 

I am trying with below script by using schedule job.


var dt = new GlideDate();
months = gs.getProperty('TSF.Months.To.Remove.User.Roles', 3) * -1;//
dt.addMonths(months);
var grUser = new GlideRecord('sys_user');
grUser.addQuery('last_login', '<', dt).addOrCondition('last_login', '');
grUser.addQuery('sys_id','4713c93ddbe5cf00077df3d31d9619e1');//checking with one user
grUser.addQuery('sys_created_on','<',dt);

grUser.query();
while (grUser.next()) {

if (checkapproverGroup(grUser.sys_id + '')) {
continue;
}

function checkExcludeGroups(grUser) {
var grGM = new GlideRecord('sys_user_grmember');
grGM.addQuery('user', grUser);

 

Here we need to check  ex : if user is member of 4 groups we need to remove 3 groups from user profile and remaining one group we need skip it because that is required group for all users .

 

 

How to achieve this..

 

 

Best Regards,

Nani

 

5 REPLIES 5

Shaikh Mzhar
Tera Guru

Hi @Nani18 

 

  1. Create a custom script field in the User [sys_user] table to store the last login time.

  2. Write a script that retrieves all users from the User [sys_user] table and checks each user's last login time. If the user's last login time is before 3 months, the script will remove all groups from the user's profile except the ABC group.

var threeMonthsAgo = new GlideDateTime();
threeMonthsAgo.addMonths(-3);

var gr = new GlideRecord('sys_user');
gr.query();
while (gr.next()) {
  var lastLogin = gr.getValue('last_login_time');
  if (lastLogin < threeMonthsAgo) {
    var user = new GlideRecord('sys_user');
    user.get(gr.getValue('sys_id'));
    var groups = user.getValue('groups');
    var newGroups = [];
    for (var i = 0; i < groups.length; i++) {
      if (groups[i].getDisplayValue() == "ABC") {
        newGroups.push(groups[i]);
      }
    }
    user.setValue('groups', newGroups);
    user.update();
  }
}

 

Please hit helpful to remove from unanswered question list.