Skip to content
29 changes: 29 additions & 0 deletions Server-Side Components/Scheduled Jobs/ReadME.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
Purpose of the Script:
This script automatically finds and cleans up user accounts that meet all of the following conditions:
* The user is inactive
* The user is locked out
* They haven’t been updated in the last 90 days

For such users, the script:
* Removes them from all groups
* Deletes all their roles
* Logs everything in the system logs

Explanation:
1. Set a time threshold (90 days):
* It calculates the date 90 days ago from today.
2. Find target users:
* Searches the sys_user table for users who:
* Are marked as inactive
* Are locked out
* Have not been updated since 90 days ago
3. Loop through each matching user:
* Logs the username being cleaned up
4. Remove user from all groups:
* Searches the sys_user_grmember table (group memberships)
* Deletes all group entries related to the user
5. Remove all roles:
* Searches the sys_user_has_role table
* Deletes all roles assigned to the user
6. Logs the total number of users processed.
7.
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// Number of days threshold
var daysThreshold = 90;
var cutoffDate = new GlideDateTime();
cutoffDate.addDaysUTC(-daysThreshold);

gs.info('🔍 Starting cleanup of inactive and locked out users since: ' + cutoffDate);

// Query users inactive, locked out, and not updated in last 90 days
var userGR = new GlideRecord('sys_user');
userGR.addQuery('active', false);
userGR.addQuery('locked_out', true);
userGR.addQuery('sys_updated_on', '<=', cutoffDate);
userGR.query();

var userCount = 0;

while (userGR.next()) {
var userSysId = userGR.getUniqueValue();
var userName = userGR.name;

gs.info('🧹 Cleaning up user: ' + userName + ' (' + userSysId + ')');

// Remove from all groups
var groupMemberGR = new GlideRecord('sys_user_grmember');
groupMemberGR.addQuery('user', userSysId);
groupMemberGR.query();
while (groupMemberGR.next()) {
gs.info('❌ Removing user from group: ' + groupMemberGR.group.name);
groupMemberGR.deleteRecord();
}

// Remove all roles
var roleGR = new GlideRecord('sys_user_has_role');
roleGR.addQuery('user', userSysId);
roleGR.query();
while (roleGR.next()) {
gs.info('❌ Removing role: ' + roleGR.role.name);
roleGR.deleteRecord();
}

userCount++;
}

gs.info('✅ Cleanup complete. Total users processed: ' + userCount);
Loading