Remove Group membership for ITIL user if inactive for 3 months
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
03-15-2023 10:24 AM
Hello Everyone,
I want to remove the group membership for ITIL users, if the user is inactive for more than 3 months. I want to run a schedule job weekly basis.
Can you please help me with script.
Thank you.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
03-15-2023 10:58 AM
// Set the date threshold for inactivity (3 months ago)
var dateThreshold = new GlideDateTime();
dateThreshold.addMonths(-3);
// Get all ITIL users who haven't logged in since the threshold date
var gr = new GlideRecord('sys_user');
gr.addQuery('active', 'false');
gr.addQuery('last_login', '<', dateThreshold);
gr.addQuery('user_name', '!=', 'admin'); // exclude admin user
gr.addQuery('roles', 'IN', 'itil'); // only ITIL users
gr.query();
while (gr.next()) {
// Remove ITIL group membership
gr.removeRole('itil');
}
gs.log('Removed ITIL group membership for inactive ITIL users.');
To schedule this script to run on a weekly basis, you can create a scheduled job in ServiceNow. Here are the steps:
- Go to System Scheduler > Scheduled Jobs.
- Click New.
- Enter a name for the job (e.g. "Remove ITIL group membership for inactive users").
- Copy and paste the script into the Script field.
- Set the Run field to Weekly.
- Set the Start field to the date and time you want the job to start.
- Click Submit.
That's it! The job will now run on a weekly basis and remove ITIL group membership for inactive ITIL users.
Please mark my reply as Helpful and/or Accept Solution, if applicable. Thanks!

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
03-15-2023 11:21 AM
var lastdate = new GlideDateTime();
lastdate.addMonths(-3);
// Users who haven't logged in since last 3 months
var gr = new GlideRecord('sys_user');
gr.addQuery('active', 'false');
gr.addQuery('last_login', '<', lastdate);
gr.addQuery('user_name', '!=', 'admin'); // exclude admin user
gr.query();
while (gr.next()) {
var grMember = new GlideRecord('sys_user_grmember');
grMember.addQuery('user', gr.sys_id);
grMember.addQuery('group', 'sys id of itil group')
grMember.query()
if (grMember.next()) {
grMember.deleteRecord() // delete user from ITIL group
}
To schedule this script to run on a weekly basis, you need to create a scheduled job in ServiceNow or you can use flow designer and add this script in flow and set them to run on weekly basis.
If my answer solved your issue, please mark my answer as Correct & or Helpful based on the Impact.