Remove users from the group

Dileep2
Tera Contributor

Hi all,

schedule job to remove the users from the particular groups who not logged in for 60 days in servicenow.

If user is part of some groups and if he hasn’t logged in for 60 days.

Thank you.

Please suggest 

6 REPLIES 6

Hello Sunil,

Thanks for the response. Could you please help in using the system property in scheduled job because groups as in future if we may want to increase the assignment groups for checking 

@Dileep2 

You can use below updated code:

 

// Define the number of days for the threshold
var daysThreshold = 60;
var currentDate = new GlideDateTime();
currentDate.setDisplayValue(currentDate);

// Calculate the date threshold (60 days ago)
var thresholdDate = new GlideDateTime();
thresholdDate.subtractDaysLocalTime(daysThreshold);

var assignmentGroupsStr = gs.getProperty('scheduled_job.assignment_groups');
var assignmentGroups = assignmentGroupsStr.split(',');

// Query users who haven't logged in for 60 days
var userGr = new GlideRecord('sys_user');
userGr.addQuery('last_login', '<', thresholdDate);
userGr.query();

while (userGr.next()) {
    // Get the user's ID
    var userId = userGr.sys_id.toString();
    
    var groupGr = new GlideRecord('sys_user_grmember');
    groupGr.addQuery('user', userId);
    groupGr.query();
        while (groupGr.next()) {
        var groupId = groupGr.group.toString();
        var groupName = groupGr.group.getDisplayValue(); 
        
        // Check if the user is a member of any of the specified assignment groups
        if (assignmentGroups.indexOf(groupName) !== -1) {
            // Remove the user from the group
            groupGr.deleteRecord();
        }
    }
}

 

Please Mark âś…Correct if this solves your query and also mark đź‘ŤHelpful if you find my response worthy based on the impact.

 

Thanks